2
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?

Column等のchildrenに特定の条件でだけ複数のWidgetを渡したい時に使えるテクニック

Posted at

ある条件の時だけColumnに追加でWidgetを表示したい時がある

それが一つのWidgetの時は以下のようにすればいい

class SampleView extends StatelessWidget {
  const SampleView({super.key, required this.hoge});
  final String? hoge;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const Text('ガハハ'),
        // hogeがnon nullの時Textを表示する
        if (hoge != null) Text(hoge!),
      ],
    );
  }
}

例えば他のWidgetとの間にスペースを取りたい時どうすればいいか
Paddingを追加したり、SizedBoxとTextをまとめたWidetとして切り出すこともできるが、スプレッド演算子でも対応できる

class SampleView extends StatelessWidget {
  const SampleView({super.key, required this.hoge});
  final String? hoge;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const Text('ガハハ'),
        // hogeがnon nullの時Textを表示する
        if (hoge != null) ...[
          // hogeを表示する時だけSizedBoxも表示したい
          const SizedBox(
            height: 4,
          ),
          Text(hoge!),
        ],
      ],
    );
  }
}

これはSizedBoxとTextを持つListを作り、スプレッド演算子でそれを一気に追加している

2
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
2
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?