【问题标题】:NoSuchMethodError : The method 'map' was called on nullNoSuchMethodError : 在 null 上调用了方法“map”
【发布时间】:2019-12-23 16:52:03
【问题描述】:

有时 animals.relatives 为空,因此 t.name 返回导致问题的 null

我尝试了 if else 语句并尝试 catch,但我猜它在小部件中不起作用?我不知道为什么它不起作用

Column(
  children: <Widget>[
    Text(animals.name),
    Text(animals.desc),
    Text("Relatives :"),
    Row(
      children: animals.relatives.map((t) => 
        FilterChip(
          label: Text(t.name),onSelected: (b){}))
         .toList(),
     ),
   ]),

如果 t.name 为空,我希望其上方的行和文本不显示

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以为此使用 collection-if

    ..,
    children: <Widget>[
     ..,
     Text('Relatives: '),
     if (animals.relatives != null &&
         animals.relatives.isNotEmpty &&
         animals.relatives.where((t) => t != null).isNotEmpty)
       Row(
         children: animals.relatives.where((t) => t != null).map(..).toList(),
       ),
    ],
    

    这可确保仅当您的变量既不为空也不为空时才包含Row
    此外,所有null 的元素都被排除在外从列表中,当只有 null 元素时,不会构建 Row

    【讨论】:

    • 感谢您的回复,这仅适用于 Row(),但如果它为空,我希望它上面的文本也不要显示
    猜你喜欢
    • 2020-01-25
    • 2021-10-25
    • 2019-07-09
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2021-11-30
    • 2021-03-11
    • 2021-09-29
    相关资源
    最近更新 更多