'Android Studio - Dart Code formatting problems

I've been trying different configurations in the code-formatting settings from Android-Studio, but the results have been pretty disappointing (and triggering) so far.

This is what the reformat code does without the dartfmt tool (notice line 94 - 110): enter image description here

dartfmt does a better job of it, but the indentation is horrible (line 91 - 96) and very inconsistent with seemingly no settings to configure for it: enter image description here

This is what I would want it to look like: enter image description here

What settings do I need to change to achieve this? It's currently pretty hard to read the code.



Solution 1:[1]

Deeply nested code is quite challenging to format and when the remaining space in lines become too short dartformat unindents to be able to format the rest of the code better.

It's better to avoid deeply nested code and instead refactor parts into their own function/method or if it is a Flutter build method, into widgets.

If you still think the behavior is invalid, please create an issue in dart-lang/dart_style and the maintainer will very likely respond with a profound answer.

Solution 2:[2]

You can't configure dartfmt. This is voluntary. But dartfmt uses trailing comma as it's core to determine where to go to newline.

The following :

foo({String foo, String bar}) {}

void main() {
  foo(foo: "Hello", bar: "Hello");
}

will stay unchanged when running dartfmt.

But simply changing to foo call to :

  ...bar: "Hello",);

will reformat it to :

foo({String foo, String bar}) {}

void main() {
  foo(
    foo: "Hello",
    bar: "Hello",
  );
}

Solution 3:[3]

It is too late but it can help.

In Android Studio go to

File > Settings > Editor > Code Style > Dart

and increase the value of Line Length.

Solution 4:[4]

If you are an Android Developer and cannot leave Android Studio, since it's your coding home, but can't let go of flutter either.

Changing tab size won't work through Default.xml in codestyles.

Use a different theme: Visual Studio 2019 Dark Theme (this auto adjusts indentation and makes code look exactly as of Visual Studio Code). To install theme - plugins -> search "Visual Studio 2019 Dark Theme"

OR

Use a different font: I prefer

Font : "Droid Sans Mono Slashed" or "Monospaced" (You can use any that works for spacing)

Font size: 18 , Line Height 1.4 // For 14 inch screens

Font size: 14 , Line Height 1.2 // For 15.6 inch screens or larger

enter image description here

OR

A combination of above looks beautiful.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Günter Zöchbauer
Solution 2 Rémi Rousselet
Solution 3 jamal
Solution 4 Vaibhav Aggarwal