Parbat Tamang
Parbat Tamang

Reputation: 81

Why are trailing commas auto deleted and not formatted in flutter?

The trailing commas used to be auto formatted now does not format it but instead it deletes them. The same happens in Android Studio. What might cause this? This is the dart settings:

"[dart]": {
    "editor.formatOnSave": true,
    "editor.formatOnType": true,
    "editor.selectionHighlight": false,
    "editor.tabCompletion": "onlySnippets",
    "editor.wordBasedSuggestions": "off"
},

I tried reinstalling dart extension but same problem. The extension is what caused it but I do not know how to fix this.

Dart Version:
Dart SDK version: 3.7.0-259.0.dev

Dart-Code Extension Version: 3.102.0

Upvotes: 8

Views: 427

Answers (3)

user3249027
user3249027

Reputation: 542

See Dans and Mayvas answers.

And maybe checkout FVM - Simple Flutter Version Management

FVM streamlines Flutter version management. It allows per-project SDK versions, ensuring consistent app builds and easier testing of new releases

Upvotes: 0

Mayvas
Mayvas

Reputation: 860

Open your pubspec.yaml file and replace:

environment:
  sdk: ^3.7.0

with

environment:
  sdk: ">=3.6.0 <4.0.0"

This change adds backward compatibility for code formatting, making it work like in older versions. The reasoning behind the new formatting is unclear, but it feels extremely uncomfortable to use.

Upvotes: 3

Dan R
Dan R

Reputation: 1326

You are likely using the new Dart formatter introduced with Dart SDK version 3.7. One of the new features are automated trailing commas, see this issue:

The rule for adding and removing them is simple:

  • If a comma-separated construct is split across multiple lines, then add a trailing comma after the last element. This applies to argument lists, parameter lists, list literals, map literals, set literals, records, record types, enum values, switch expression cases, and assert arguments.

  • Conversely, if the formatter decides to collapse a comma-separated construct onto a single line, then do so and remove the trailing comma.

In other words: If the collection fits into one line, the formatter automatically deletes your trailing comma, and formats the code accordingly.

Upvotes: 4

Related Questions