Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 878
Mahmoud Hassan Al-Ridini Avatar asked Sep 18 '25 09:09

Mahmoud Hassan Al-Ridini


2 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(),
)
like image 186
CopsOnRoad Avatar answered Sep 19 '25 22:09

CopsOnRoad


You cannot use as to cast List<T?> to List<T> because they are not directly related types; you would need to cast the elements instead, using List<Widget>.from() or Iterable.cast<Widget>().

See Dart convert List<String?> to List nnbd for how to remove null elements from a List<T?> and get a List<T> result (and thus avoiding the need to cast later).

like image 41
jamesdlin Avatar answered Sep 19 '25 22:09

jamesdlin