[Solved] Flutter format document not working

I have been using Android Studio for Flutter project. Some of my friends suggested me to give a try to Visual Studio Code as well. I like Visual Studio Code for javascript, typescript and ReactJS projects. So, thought of giving it a try. So, I followed Get Started from official docs. After sometime, I found out that my flutter code format were not working as expected. I started getting error as “Extension ‘Flutter’ cannot format ‘lib/body.dart'” here ‘lib/body.dart’ is file that I was trying to format. My initial thought was perhaps it could have happened due to syntax errors. But, I couldn’t see any error in visual studio code. See the screenshot below for the source code of ‘body.dart’. Look at Editor status bar for format error.

Source code body.dart
Source code body.dart

But, I was able to format it using flutter format command. So, I was sure that it could be editor settings that could have caused it. So, I looked at editor settings again (settings.json). My dart format configuration is as below.

"[dart]": {
  "editor.defaultFormatter": "Dart-Code.flutter",
  "editor.formatOnSave": true
},

No error on this configuration, right!. Well, this seems to be the actual problem. I am going to borrow statement from github issue comment from https://github.com/Dart-Code/Dart-Code/issues/1274#issuecomment-587549984 “The dart formatter is in the Dart extension (Dart-Code.dart-code) rather than the Flutter one”. So, there are two solutions for this problem.

1. Disable [dart] formatter that was added to settings.json
2. Use proper dart formatter “Dart-code.dart-code”

I opted to use “Dart-code.dart-code” as it allows us to have more control over format configurations. My configuration after changing to right dart formatter.

  "[dart]": {
    "editor.defaultFormatter": "Dart-Code.dart-code",
    "editor.formatOnSave": true
  },

Now, whenever I save my dart file, it also gets formatted nicely. I hope this helps you to solve your formatting issue as well.

Resources that were helpful to debug this problem.

https://github.com/Dart-Code/Dart-Code/issues/1274#issuecomment-587549984

Leave a Reply

Your email address will not be published. Required fields are marked *