This section will introduce best practices and coding standards in Flutter development.
Code Standards
Naming Conventions
| Type | Rule | Example |
|---|---|---|
| Class Name | Big CamelCase | MyHomePage |
| Function/Variable | Small CamelCase | userName, getData |
| Constant | Big CamelCase + k prefix | kMaxCount |
| File | Lowercase + Underscore | my_home_page.dart |
Example: Correct Naming
// Class name - Big CamelCase
class UserProfilePage extends StatelessWidget {}
// Function - Small CamelCase
void fetchUserData(){}
// Variable - Small CamelCase
String userName ='Zhang San';
// Constant - k prefix
const int kMaxRetryCount =3;
const String kAppName ='My Application';
// Enum - Big CamelCase
enum AppState { loading, success, error }
// File name - lowercase with underscore
// user_profile_page.dart
Performance Optimization
1. Avoid Unnecessary Rebuilds
Example: Using const Constructor
// Recommended: Use const to reduce rebuilds
const Text('Hello')// Won't rebuild
const SizedBox(width:10)
// Avoid: Creates new object on every build
Text('Hello')// Will rebuild
// Use const in lists
ListView(
children:const[
Text('A'),
Text('B'),
Text('C'),
],
)
2. Use Keys to Optimize List Performance
Example: Correct Use of Keys
// Add unique key to list items
ListView.builder(
itemCount: items.length,
itemBuilder:(context, index){
return ListTile(
key: ValueKey(items.id),// Use unique identifier as key
title: Text(items.name),
);
},
)
3. Lazy Load List Items
Example: Using ListView.builder
// Recommended: Use builder for lazy loading
ListView.builder(
itemCount:1000,// Must use for large lists
itemBuilder:(context, index){
return ListTile(title: Text('Item $index'));
},
)
// Avoid: Using children to build large lists
ListView(
children: List.generate(1000,(i)=> Text('Item $i')),
)
Project Structure
Example: Recommended Project Structure
// lib/
// βββ main.dart # Entry file
// βββ app.dart # App configuration
// βββ core/ # Core functionality
// β βββ constants/ # Constants
// β βββ theme/ # Theme
// β βββ utils/ # Utilities
// β βββ extensions/ # Extensions
// βββ data/ # Data layer
// β βββ models/ # Data models
// β βββ repositories/ # Repositories
// β βββ services/ # Network services
// βββ domain/ # Domain layer
// β βββ entities/ # Entities
// βββ presentation/ # Presentation layer
// β βββ pages/ # Pages
// β βββ widgets/ # Widgets
// β βββ providers/ # State management
// βββ routes/ # Routes
Error Handling
Example: Global Error Handling
void main(){
// Global exception capture
FlutterError.onError=(details){
// Log error
print('Flutter Error: ${details.exception}');
// Report error to server
reportError(details.exception);
};
// Zone exception capture
runZonedGuarded((){
runApp(const MyApp());
},(error, stackTrace){
print('Zone Error: $error');
reportError(error);
});
}
Following best practices can make code more maintainable, perform better, and reduce bugs in production environments.
YouTip