type 'List<Widget?>' is not a subtype of type 'List<Widget>' in type cast

Viewed 1521

After running dart migrate & applying null safety, that error popped up at my code and I think that's the error causing code block.

LayoutBuilder(builder: (context, cons) {
  return GestureDetector(
    child: new Stack(
      children: <Widget?>[
        // list of different widgets 
        .
        .
        .
      ].where((child) => child != null).toList(growable: true) as List<Widget>,
    ),
  );
),

The error message says:

The following _CastError was thrown building LayoutBuilder:
type 'List<Widget?>' is not a subtype of type 'List<Widget>' in type cast

The relevant error-causing widget was
LayoutBuilder
package:projectName/…/components/fileName.dart:182

If anyone encountered this issue, how it can be solved?

3 Answers

Although there are different ways to solve it as provided here by @jamesdlin but the recommended one is to use whereType. For example:

List<Widget?> nullableWidgets = [];
List<Widget> nonNullable = nullableWidgets.whereType<Widget>().toList();

To answer your question:

Stack(
  children: <Widget?>[
    // Widgets (some of them nullable)
  ].whereType<Widget>().toList(),
)

Not a Dart expert.

But it seems like the compiler does not respect your null safety checkup.

I suggest creating a new List<Widget> and populate it with each item from List<Widget?> which is not null.

Related