I'm new to Flutter and haven't found much success in my brief online search for an answer to this, which is the reason for this post.
Here's the code in question:
// `myList` can potentially be null.
children: widget.myList?.map((item) {
return Text("Hi.");
}).toList(),
I'm trying to loop over a List<String>?
of errors in my stateful widget, inside of the children:
property of a Column
.
Dart is telling me that I cannot map
over a List<String>?
, and suggests that I use myList?.map
instead.
However, when I do that, the issue now becomes that children:
expects a List<Widget>
and can therefore not accept a List<Widget>?
...
I seem to be stuck in circuitous errors, but somehow I feel the solution is simple. I'm still learning about null-safety.
So tl;dr:
How do I reconcile between a potentially null list of widgets, and a property that expects a list of widgets that isn't null?
Solution
children: myList?.map((e) => Text(e)).toList() ?? [],
CodePudding user response:
If your List
is List<Widget>?
, you can add simply a null
check like so:
children: _widgets?.map((item) => item).toList() ?? [Text('List was null')],
If your List
is List<Widget?>?
you can change it to:
children: _widgets?.map((item) => item ?? Text('widget was null')).toList() ?? [Text('List was null')],
If you want to map a List<String?>
inside a Column
Column(
children: _strings.map((e) => Text(e ?? 'String was null')).toList(),
)
OR
Column(
children: _strings.map((e) => e == null ? Text('was null') : Text(e)).toList(),
)
If your List
is List<String>?
Column(
children: _strings?.map((e) =>Text(e)).toList() ?? [Text('The list was null')],
)