3

在运行dart migrate并应用 null 安全性之后,我的代码中弹出了该错误,我认为这是导致代码块的错误。

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

如果有人遇到这个问题,如何解决?

4

3 回答 3

3

尽管@jamesdlin提供不同的方法来解决它,但推荐的方法是使用. 例如:whereType

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

要回答您的问题:

Stack(
  children: <Widget?>[
    // Widgets (some of them nullable)
  ].whereType<Widget>().toList(),
)
于 2021-05-22T14:35:34.707 回答
1

您不能使用asto cast List<T?>toList<T>因为它们不是直接相关的类型;您需要使用or来转换元素List<Widget>.from()Iterable.cast<Widget>()

请参阅Dart convert List<String?> to List nnbd了解如何null从 a 中删除元素List<T?> 获得List<T>结果(从而避免以后需要强制转换)。

于 2021-03-05T20:05:41.847 回答
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.

于 2021-03-05T19:40:15.557 回答