Before Flutter introduced the null-safety feature, I was able to conditionally add Widgets within a list like so:
actions: <Widget>[
canCancel
? CupertinoDialogAction(
child: Text(cancelActionText),
onPressed: () {
Navigator.pop(context);
},
)
: null,
].where(notNull).toList()
notNull
being a homemade filter that filters off the null objects...
Now with null-safety it's impossible because the list of Widgets strictly has to be non-null. What would be a better approach?
Just use if
inside the List
:
<Widget>[
if (true) Widget(),
]
Example with your code:
actions: <Widget>[
if (canCancel)
CupertinoDialogAction(
child: Text(cancelActionText),
onPressed: () {
Navigator.pop(context);
},
),
]
Just replace your null with an empty, size zero, SizedBox
.
SizedBox(width: 0, height: 0)
Or as suggested in comments:
SizedBox.shrink()
As YoBo suggested , using collection- if
is the better approach here, but if for some reason you need to be able to store null
s in a List
and filter them out later (or if you just prefer your existing style), you can:
List
type to allow nullable elements. That is, use <Widget?>[]
instead of <Widget>[]
.Iterable.whereType
with a non-nullable type to filter out null
values.actions: <Widget?>[
canCancel
? CupertinoDialogAction(
child: Text(cancelActionText),
onPressed: () {
Navigator.pop(context);
},
)
: null,
].whereType<Widget>().toList();
if
is not new as it was added in Dart 2.3 a few years ago. Even before null-safety, you were not allowed to return a null
for a widget. You might not see a compile-time warning before NNBD, but it is a runtime error.
As I mentioned in this answer (although that answer isn't for your case), you can use if
condition or even ternary operator like this:
Column(
children: [
if (condition) Text(''),
condition ? Text('') : Container(),
],
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.