- Automatically formatting code
Automatically formatting code
While your code may follow any preferred style – in our experience – teams of developers may find it more productive to:
have a single, shared style, and
to enforce this style through automatic formatting.
The alternative is often tiring formatting debates during code reviews, where time may be better spent on code behavior rather than code style.
Automatically formatting code in IntelliJ
Automatic formatting of code is supported in IntelliJ if you have the
Dart plugin (see IntelliJ setup).
To automatically format the code in the current source code window, right-click
in the code window and select
Reformat with Dart style. You can add a keyboard
shortcut to this in Keymap section of IntelliJ Preferences.
Automatically formatting code with the
You can also automatically format code in the command line interface (CLI) using
flutter format command:
Usage: flutter format <one or more paths> -h, --help Print this usage information.
Using ‘trailing commas’
Flutter code often involves building fairly deep tree-shaped data structures,
for example in a
build method. To get good automatic formatting, we recommend
you adopt the optional trailing commas. The guideline for adding a trailing
comma is simple: Always add a trailing comma at the end of a parameter list in
functions, methods, and constructors where you care about keeping the formatting
you crafted. This will help the automatic formatter to insert an appropriate
amount of line breaks for Flutter-style code.
Here is an example of automatically formatted code with trailing commas:
And the same code automatically formatted code without trailing commas: