Scaraux
Scaraux

Reputation: 4152

Flutter null safety conditional widget

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?

Upvotes: 5

Views: 6276

Answers (4)

CopsOnRoad
CopsOnRoad

Reputation: 267464

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(),
  ],
)

Upvotes: 1

J. S.
J. S.

Reputation: 9625

Just replace your null with an empty, size zero, SizedBox.

SizedBox(width: 0, height: 0)

Or as suggested in comments:

SizedBox.shrink()

Upvotes: 5

YoBo
YoBo

Reputation: 2529

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);
           },
      ),
]

Upvotes: 17

jamesdlin
jamesdlin

Reputation: 89946

As YoBo suggested, using collection-if is the better approach here, but if for some reason you need to be able to store nulls in a List and filter them out later (or if you just prefer your existing style), you can:

  1. Change your List type to allow nullable elements. That is, use <Widget?>[] instead of <Widget>[].
  2. Use 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();

Upvotes: 2

Related Questions