Best Practices and Tips in Flutter
Any programming language needs to improve code quality, readability, maintainability, and robustness so in the future when we have to work on that app we can easily find specific code.
Let’s see some best practices for designing and developing the flutter app.
Give names of variables, constants, parameters, and named parameters in lowerCamelCase.
(1)Don’t initialize variables null
In Dart, any variables are automatically initialized null when their values are not specified.
(2)Naming convention:
Give the name of any Class, extension, enums in UpperCamelCase.
(3)Packages, Libraries, source files should be in snake_case.
(4)Use relative imports for files in lib
When we using relative imports together then it’s possible to create confusion when the same class gets imported from two different ways.
To avoid that case we should have to use a relative path in the /lib folder.
(5)Use ?? and ?. operators
In dart to check nullability of variables use ?? (if null) and ?. (null aware) operators instead of checks null in a conditional expression.
(6)Use Cascades Operator
If we want to do a sequence of operations on the same object then we should use the Cascades(..) operator.
(7)Use debugPrint() for logging in to the console.
For logging in to the console if you use print() and output is in too many lines, then Android sometimes discards some logs line. To avoid this use debugPrint().
(8)Use const in widgets
When setState call all widgets will rebuild so it’s a decrease performance. so define const to those widgets which will not change when setState call.
(9)Reusability of code
When some code is used multiple times without any changes at that time don’t write the same code multiple times .make one widget for that and use that widget when it needs.
(10)Bulk declaration
If you declaring each variable separately, you can declare a variable of the same datatype at once.
(11)Use GoogleFonts
When you have to use google fonts in a flutter, don’t need to download that font. you can directly use google font using GoogleFonts.FontName().