🥦

【Dart/Flutter】if文によるWidget表示(「...」演算子でList<Widget>として複数表示)

2022/06/09に公開

【Dart/Flutter】if文によるWidget表示(「...」でList<Widget>として複数表示)

  • 実行環境
    • DartPadやAndroid Studio等で実行
      • Based on Flutter 3.0.1 Dart SDK 2.17.1
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: const <Widget>[
            if (true) Text('1:displayed'),
            if (false) Text('2:not displayed'),
            if (true) ...[
              Text('3:displayed'),
              Text('4:displayed'),
            ],
            if (false) ...[
              Text('5:not displayed'),
              Text('6:not displayed'),
            ],
            Text('7:displayed'),
          ],
        ),
      ),
    );
  }
}

実行結果※画面イメージ

1:displayed
3:displayed
4:displayed
7:displayed

Discussion