Update on 16/11/2020:
import_sorter just released 4.3.1, which provides us a way to sort only a subset of files rather than sorting all of them. We can integrate it into our workflow more nicely, see the updated
lefthook.yml at the end of this article.
As the team size grows, coding standard is very important to maintain an easily understood and consistent codebase. In this article I will share how I setup and integrate it into my workflow.
Choosing linting rules
Flutter comes with a code linter in the SDK, all you have to do is create a file
analysis_options.yaml in your project root, you may find all the available rules here: Linter for Dart.
If you are too busy too choose your own rules, you may use mine:
After that, run code linting by:
If you use Visual Studio Code like me, you may install the flutter extension and the result of linting will be realtime updated in the terminal.
Sorting imports automatically
For large projects there may be lots of
import statements on top of some files, it would be easier for the eye (and for managing, or course), to sort them alphabetically.
import_sorter is doing a great job here, install it then run:
flutter pub run import_sorter:main
And boom! All your
import statements will be categorised and sorted like:
// Dart imports:
// Flutter imports:
// Package imports:
// Project imports:
It does have some flexibility for you to config, in case if you want to ignore some files, or want to add emojis in your files.
Formatting the code
Flutter comes with a code formatter in the SDK, here is how to use it:
flutter format lib
If you use Visual Studio Code, you may turn on the following setting:
Integrating with the Git workflow
It feels very dumb for us to run the three commands every time we do
git commit, so we are going to automate the workflow.
lefthook, which is a fast and powerful Git hooks manager for projects of any languages:
# for Mac and brew users:
brew install Arkweid/lefthook/lefthook# or you may find the installation method here:
After that, navigate to the root of your project, run:
This command will patch your
.git/hooks folder to insert some scripts to it. Note that it is done locally and will not be pushed to your git server, so you need to do it once on every development machine.
You may notice that there is a new file called
lefthook.yml, let’s open it and modify the content to (or customise it to suit your needs):
Try committing any changes by
git, you should see the commands are executed automatically, and it blocks the commit if any of the commands failed.
So this is how you could enforce coding standards in your flutter projects, what do you guys think? Feel free to tell me if it helps, or if you have any ideas to further improve it.
Do you know you can clap up to 50 times for an article? Go smash that button!