输入"List< Widget?>"不是'List< Widget>'类型的子类型铸型

输入

问题描述:

运行飞镖迁移后,应用null安全性时,该错误会在我的代码中弹出,我认为这是导致代码阻塞的错误.

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 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?

您不能使用 as List< T?> 强制转换为 List< T> ,因为它们不是直接相关的类型;您需要使用 Iterable.cast< Widget>() .

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

请参见 Dart convert List< String?>列出nnbd ,以了解如何从 List< T?> 中删除 null 元素,并获得 List<T> 结果(从而避免了以后再投放).

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