How to conditionally add widgets to a list?

后端 未结 3 1987
醉酒成梦
醉酒成梦 2020-12-30 00:01

In flutter, widgets such as Row/ListView/Stack don\'t handle null children. So if we want to conditionally add widgets as children I u

相关标签:
3条回答
  • 2020-12-30 00:23

    The new Dart syntax allows 'if' in lists, which leads to this simple solution:

    Row(
      children: <Widget>[
        if (foo == 42) Text("foo"),
      ],
    );
    
    0 讨论(0)
  • 2020-12-30 00:24

    EDIT:

    Since Dart 2.2, new syntaxes supports this natively:

    Column(
      children: [
        if (foo != null) Text(foo),
        Bar(),
      ],
    );
    

    This problem is currently debated on github here.

    But for now, you can use dart sync* functions:

    Row(
      children: toList(() sync* {
        if (foo == 42) {
          yield Text("foo");
        }
      }),
    );
    

    where toList is:

    typedef Iterable<T> IterableCallback<T>();
    
    List<T> toList<T>(IterableCallback<T> cb) {
      return List.unmodifiable(cb());
    }
    

    Not only it solves the conditional addition problem; it also allows for a "spread operator" thanks to yield*. Example:

    List<Widget> foo;
    
    Row(
      children: toList(() sync* {
        yield Text("Hello World");
        yield* foo;
      }),
    );
    
    0 讨论(0)
  • 2020-12-30 00:37

    Here's a simpler version I use:

    Row(
      children: [
        Text("always included"),
        skipNulls([
          icon,
          label,
        ]),
      ],
    );
    
    skipNulls<T>(List<T> items) {
      return items..removeWhere((item) => item == null);
    }
    
    0 讨论(0)
提交回复
热议问题