4

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?

4
  • simply delete the ? Commented Mar 5, 2021 at 19:27
  • I tried but it didn't work. @Irsvmb Commented Mar 5, 2021 at 19:31
  • The children widgets of the stack goes red when I remove the " ? " Error message is: `the element type 'container?' can't be assigned to list type 'Widget'. for example @lrsvmb Commented Mar 5, 2021 at 19:38
  • Due to null safety restrictions removing all of them would cause another problem. Commented Mar 5, 2021 at 21:14

3 Answers 3

4

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(),
)
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.