Search code examples
flutterdartvisual-studio-codecode-formatting

Proper flutter/dart formatting


I am working in some flutter code. The code stacks closing braces on the same line. In addition, when I run "Format Document" in VSCode, it also stacks the braces on a single line.

Like this (see last line)...

return Container(
    width: 200,
    child: CupertinoTextField(
        maxLength: 10,
        textCapitalization: TextCapitalization.characters,
        focusNode: focusNode,
        decoration: BoxDecoration(
            border: Border.all(color: Colors.white.withOpacity(0))),
        style: accentTextStyle,
        placeholder: "NAME",
        textAlign: TextAlign.center,
        keyboardAppearance: Brightness.dark,
        controller: _textController,
        onChanged: (s) {
          navigation.update();
          if (s == '') {
            program.name = 'UNNAMED${navigation.programsCounter}';
            return;
          }
          program.name = s.toUpperCase();
        }));

But in the flutter docs and example code, all of the examples use the follow format (where braces are on separate lines).

return Container(
  width: 200,
  child: CupertinoTextField(
    maxLength: 10,
    textCapitalization: TextCapitalization.characters,
    focusNode: focusNode,
    decoration: BoxDecoration(
        border: Border.all(color: Colors.white.withOpacity(0))),
    style: accentTextStyle,
    placeholder: "NAME",
    textAlign: TextAlign.center,
    keyboardAppearance: Brightness.dark,
    controller: _textController,
    onChanged: (s) {
      navigation.update();
      if (s == '') {
        program.name = 'UNNAMED${navigation.programsCounter}';
        return;
      }
      program.name = s.toUpperCase();
    }
  )
);

Which is the proper format? Also, does "Format Document" use the dart extension to get the proper format?


Solution

  • You can use comma(,) at the end of the braces. Then the 'Format Document' will separate the lines for each brace. Try this:

    return Container(
     width: 200,
     child: CupertinoTextField(
        maxLength: 10,
        textCapitalization: TextCapitalization.characters,
        focusNode: focusNode,
        decoration: BoxDecoration(
            border: Border.all(color: Colors.white.withOpacity(0))),
        style: accentTextStyle,
        placeholder: "NAME",
        textAlign: TextAlign.center,
        keyboardAppearance: Brightness.dark,
        controller: _textController,
        onChanged: (s) {
          navigation.update();
          if (s == '') {
            program.name = 'UNNAMED${navigation.programsCounter}';
            return;
          }
          program.name = s.toUpperCase();
        },
       ),
      );
    

    Edit:

    Ok, you are looking for the proper method. As mentioned in the official document, you should use trailing commas.

    To get good automatic formatting, we recommend you adopt the optional trailing commas.