One of the features of Flutter is a possibility to create apps in record time. However, it is very important to write Dart code properly and to use the best practices, Effective Dart, from the beginning. There are some good tools and packages that help you to apply best practices quickly.
Default IDE static analysis
Dart has a static analysis tool. Static analysis allows you to find problems before executing a single line of code. It’s a great tool used to find possible bugs and ensure that code conforms to style guidelines. When you use IDE to develop an app, Flutter tool analyzes the project’s Dart code and keeps you in a safe place. For example, when you define FloatingActionButton and forget to implement
onPressed, then IDE warns that the param
onPressed is required.
From the image above you can see that some of the lint options are commented out. But they might be useful for your project. To enable them you can create analysis options file in your project.
Analysis options file
For this, you need to place analysis_options.yaml at the root of the package, in the same directory as the pubspec.yaml file.
Here you can enable/disable linter rules, enable stricter type checks, exclude files for linter check and more. The full list of supported lint rules with documentation is always updated here. You can copy-paste all of them in your analysis_options.yaml. Or you can have a look at the analysis_options.yaml with rules that are following the Effective Dart guide.
If you don’t want to explore linter rules list for analysis_options.yaml and you’d like to start working on features as soon as possible you can give a try to pedantic package which is a good starting point that helps to write readable and effective Dart code. Documentation represents this package as default Google’s rules, that are used in their own Dart code. To use lint rules from this package, you need to add:
- a dependency in your pubspec.yaml:
- one line of code in your analysis_options.yaml:
Don’t forget to run
flutter packages get to update dependencies. And now it is time to hack away!
P.S. When you have an asynchronous app, it is expected that all your Futures are
awaited, so pedantic package has a lint rule
unawaited_futures. But sometimes you have a case when a Future is not awaited intentionally. Therefore pedantic package provides a function
void unawaited(Future<void> future)
for silencing the rule. This function may be used to ignore a particular Future.