Search code examples
fluttervisual-studio-codeprettier

How can I adjust the formatting of Flutter code in Visual Studio Code?


I would like this formatting to happen when I save the file

enter image description here

instead I get this upon save, even if I have manually formatted the code as I like.

enter image description here

my settings look like this

enter image description here

I have the flutter extension installed as well, as recommended by Flutter documentation.enter image description here


Solution

  • Add a trailing comma.

    Expense(
      {required this.title,
      required this.amount,
      required this.date,
      required this.category,})
    

    When you run dart format (or use the equivalent integrated command on VSCode), the code will be formatted to:

    Expense({
      required this.title,
      required this.amount,
      required this.date,
      required this.category,
    })
    

    The documentation has example of how trailing commas affect the formatting result: https://docs.flutter.dev/tools/formatting#using-trailing-commas

    You can also enable a lint that will tell you to always use trailing commas: https://dart.dev/tools/linter-rules/require_trailing_commas