4

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?

Scaraux
  • 3,841
  • 4
  • 40
  • 80

4 Answers4

14

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);
           },
      ),
]
YoBo
  • 2,292
  • 3
  • 9
  • 25
4

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

SizedBox(width: 0, height: 0)

Or as suggested in comments:

SizedBox.shrink()
J. S.
  • 8,905
  • 2
  • 34
  • 44
2

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();
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • This is a valid answer as well. I don't need to have null in the list though, the end goal was to conditionally insert the widget in a declarative manner. Thanks! – Scaraux Apr 13 '21 at 16:07
1

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(),
  ],
)
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440