Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally add widgets to a list?

In flutter, widgets such as Row/ListView/Stack don't handle null children. So if we want to conditionally add widgets as children I usually do the following:

Row(   children: <Widget>[     foo == 42 ? Text("foo") : Container(),   ], ); 

But this feels weird to add an empty container.

Another solution is a where filter :

Row(   children: <Widget>[     foo == 42 ? Text("foo") : null,   ].where((t) => t != null).toList(), ); 

This solves the empty container problem but we still have an ugly ternary and it is tiresome to write.

Is there any better solution?

like image 484
Rémi Rousselet Avatar asked Aug 28 '18 14:08

Rémi Rousselet


2 Answers

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;   }), ); 
like image 94
Rémi Rousselet Avatar answered Sep 18 '22 13:09

Rémi Rousselet


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

Row(   children: <Widget>[     if (foo == 42) Text("foo"),   ], ); 
like image 36
G. Marc Avatar answered Sep 19 '22 13:09

G. Marc