5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Dartコードの自動整形が崩れる

Posted at

事象

Flutterプラグインを追加したAndroid Studioには、Dartコードを自動で整形する機能があります。

多くの場合この自動整形はいい感じに整形してくれるのですが、ソースコード中にExpanded()が含まれる場合インデントが崩れます。

整形後

Expanded(
    child: Row(
  children: [   //本来このchildrenはあと4スペース分、右にあるべき
    Container(
      color: Colors.green[300],
    ),
  ],
)),

原因

VScodeのDartプラグインレポでやり取りされているissueを見ると、どうやらDartのフォーマッターの仕様のようです。

解決方法

上記の仕様はFlutter公式も把握しており、以下のように解決方法を提示しています

Flutter code often involves building fairly deep tree-shaped data structures, for example in a build method. To get good automatic formatting, we recommend you adopt the optional trailing commas. The guideline for adding a trailing comma is simple: Always add a trailing comma at the end of a parameter list in functions, methods, and constructors where you care about keeping the formatting you crafted. This helps the automatic formatter to insert an appropriate amount of line breaks for Flutter-style code.
要約:最後の要素だろうがなんだろうが、つけれるところは常にカンマをつけてね。

実際に私の例でいうと、

カンマを追加して整形
Expanded(
  child: Row(
    children: [
      Container(
        color: Colors.green[300],
      ),
    ],
  ),       //←このカンマを追加するとキレイに整形される。
),

このようにRow()の後ろにカンマを追加したらキレイに整形されました。
プログラム上意味のないカンマを置くのに少し抵抗はありますが、
インデントが崩れるよりはマシなので素直に従おうと思います。

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?