普通の書き方:
List<String> fruits = ['りんご', 'バナナ'];
List<String> vegetables = ['にんじん', 'トマト'];
List<String> foods = [];
foods.addAll(fruits);
foods.addAll(vegetables);
// 結果: ['りんご', 'バナナ', 'にんじん', 'トマト']
Dartのスマートな書き方:
List<String> fruits = ['りんご', 'バナナ'];
List<String> vegetables = ['にんじん', 'トマト'];
List<String> foods = [...fruits, ...vegetables];
// 結果: ['りんご', 'バナナ', 'にんじん', 'トマト']
もっと便利な使い方:
途中に新しい要素も追加できる:
List<String> menu = [
'サラダ',
...fruits, // りんご、バナナ が入る
'メインディッシュ',
...vegetables, // にんじん、トマト が入る
'デザート',
];
// 結果: ['サラダ', 'りんご', 'バナナ', 'メインディッシュ', 'にんじん', 'トマト', 'デザート']
Flutter でよく見る使い方
Widget build(BuildContext context) {
List<Widget> headerWidgets = [AppBar(title: Text('タイトル'))];
List<Widget> contentWidgets = [Text('内容1'), Text('内容2')];
return Column(
children: [
...headerWidgets, // ヘッダーを展開
Divider(), // 区切り線
...contentWidgets, // コンテンツを展開
],
);
}
Widgetのリストを合体!
おまけ: null かもしれないリストは …?
List<String>? extraItems = null; // null かもしれない
List<String> allItems = [
'アイテム1',
...?extraItems, // null なら何も追加しない、あれば展開する
'アイテム2',
];
// 結果: ['アイテム1', 'アイテム2']
まとめ:.. との違い
| 記号 | 読み方 | 意味 |
|---|---|---|
| .. (2個) | カスケード | 同じものに連続で命令 |
| … (3個) | スプレッド | リストの中身を展開 |
… を使うと、リストの合体がスッキリ1行で書けて便利!
