When Dart Stops Formatting Your Code the Way You Want

I have been noticing something odd for a while now. Whenever I save a Dart file, my code suddenly gets formatted, in a not very good way.

Here is what it looks like after saving:

And here is what it used to look like before:

Honestly, it is not just ugly; it also makes the code harder to read.

So, I started digging.

That's when I found out that this change came with Dart's update, which is around version 3.7.

The new formatter, no longer preservers trailing commas by default.

So.. What's the fix?

Luckily, Dart gives us a simple way to take back control.

We can run the following command in our project root to reformat all of our Dart files properly:

dart format .

But there is a small catch. You also need to tell the formatter to preserve trailing commas explicitly.

To do that, we add the following configuration in our analysis.format file:

formatter:
  trailing_commas: preserve

Once this is in place, dart format . will restore your preferred formatting style.


References

dart format
Command-line tool for formatting Dart source code.
How to Configure the Updated Code Formatter in Dart 3.8
Dart 3.8 introduced an updated formatter with various configuration options. Learn what’s new and how to prepare your codebase.

About Me

I am Zaahra, a Google Women Techmakers Ambassador who enjoy mentoring people and writing about technical contents that might help people in their developer journey. I also enjoy building stuffs to solve real life problems.

To reach me:

LinkedIn: https://www.linkedin.com/in/faatimah-iz-zaahra-m-0670881a1/

X (previously Twitter): _fz3hra

GitHub: https://github.com/fz3hra

Cheers,

Umme Faatimah-Iz-Zaahra Mujore | Google Women TechMakers Ambassador | Software Engineer