- Classes, enums, typedefs, and extensions name should in
UpperCamelCase.
class MainScreen { ... }
enum MainItem { .. }
typedef Predicate<T> = bool Function(T value);
extension MyList<T> on List<T> { ... }
- Libraries, packages, directories, and source files name should be in
snake_case(lowercase_with_underscores).
- Variables, constants, parameters, and named parameters should be in
lowerCamelCase.
Always specify the type of member when it’s value type is known. Avoid using var
when possible.
//Don't
var item = 10;
final car = Car();
const timeOut = 2000;
//Do
int item = 10;
final Car bar = Car();
String name = 'john';
const int timeOut = 20;
Many times we need to render a widget based on some condition in Row and Column. If conditional expression return null in any case then we should use if condition only.
//Don't
Widget getText(BuildContext context) {
return Row(
children: [
Text("Hello"),
Platform.isAndroid ? Text("Android") : null,
Platform.isAndroid ? Text("Android") : SizeBox(),
Platform.isAndroid ? Text("Android") : Container(),
]
);
}
//Do
Widget getText(BuildContext context) {
return Row(
children:
[
Text("Hello"),
if (Platform.isAndroid) Text("Android")
]
);
}
Prefer using ?? (if null) and ?. (null aware) operators instead of null checks in conditional expressions.
//Don't
v = a == null ? b : a;
//Do
v = a ?? b;
//Don't
v = a == null ? null : a.b;
//Do
v = a?.b;
For functions that contain just one expression, you can use an expression function. The =>
(arrow) notation is used for expression function.
//Don't
get width {
return right - left;
}
Widget getProgressBar() {
return CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
);
}
//Do
get width => right - left;
Widget getProgressBar() => CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
);
print()
anddebugPrint()
both are used for logging in the console. If you are use print()
and output is too much at once, then Android sometimes discards some log lines. To avoid this, use debugPrint().
When setState()
is called on a State, all descendent widgets will rebuild. Therefore, Split widget into small widgets so the setState()
call to the part of the subtree whose UI actually needs to change.
Also Create a Widget instead of function for component or so.
When working with infinite lists or very large lists, it’s usually advisable to use a ListView
builder in order to improve performance.
Default ListView
constructor builds the whole list at once. ListView.builder
creates a lazy list and when the user is scrolling down the list, Flutter builds widgets on-demand.
The widget which will not change when setState call we should define it as constant. It will prevent widget to rebuild so it improves performance.
Useful Links