【问题标题】:How do I map a list of potentially null widgets?如何映射可能为空的小部件列表?
【发布时间】:2021-09-12 09:03:33
【问题描述】:

我是 Flutter 的新手,在我简短的在线搜索中没有找到很大的成功,这就是这篇文章的原因。

这是有问题的代码:

// `myList` can potentially be null. 
children: widget.myList?.map((item) {
  return Text("Hi.");
}).toList(),

我正在尝试在Columnchildren: 属性内循环我的有状态小部件中的List<String>? 错误。

Dart 告诉我,我不能在 List<String>? 上使用 map,并建议我改用 myList?.map

但是,当我这样做时,现在的问题是 children: 需要 List<Widget>,因此不能接受 List<Widget>? ...

我似乎陷入了迂回错误,但不知何故,我觉得解决方案很简单。我仍在学习零安全性。

所以 tl;博士:

如何在可能为空的小部件列表和需要不为空的小部件列表的属性之间进行协调?


解决方案

children: myList?.map((e) => Text(e)).toList() ?? [],

【问题讨论】:

    标签: flutter dictionary dart


    【解决方案1】:

    如果您的ListList<Widget>?,您可以像这样简单地添加null 检查:

    children: _widgets?.map((item) => item).toList() ?? [Text('List was null')],
    

    如果您的ListList<Widget?>?,您可以将其更改为:

    children: _widgets?.map((item) => item ?? Text('widget was null')).toList() ?? [Text('List was null')],
    

    如果您想在Column 中映射List<String?>

    Column(
      children: _strings.map((e) => Text(e ?? 'String was null')).toList(),
    )
    

    Column(
      children: _strings.map((e) => e == null ? Text('was null') : Text(e)).toList(),
    )
    

    如果您的ListList<String>?

    Column(
      children: _strings?.map((e) =>Text(e)).toList() ?? [Text('The list was null')],
    )
    

    【讨论】:

    • 谢谢。这有两个问题。我认为即使它不为空,它仍然会返回List<Widget>?children: 不会接受。其次,我不希望在列表为空的情况下显示任何内容。
    • 我的名单真的是List<String>?
    • 我已经用 Column 检查了它,孩子们只接受 List<Widget> ,它工作正常。
    • 谢谢刚刚看了。因此,当我使用该确切格式时,我收到一条错误消息:error: The method 'map' can't be unconditionally invoked because the receiver can be 'null')
    • 太棒了!我采用了您的初始解决方案,并使用了?,它有效!我可以看到这也是您精心编辑的内容。所以现在可以了。很好,谢谢!唯一的区别是我使用了 ?? [] 最后,因为我不希望出现任何后备内容。我会将最终解决方案放在 OP 中。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 2019-11-25
    • 2021-08-04
    • 1970-01-01
    • 2013-08-31
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多