flutter - NoSuchMethodError : The method 'map' was called on null 错误

标签 flutter dart

有时 animals.relatives 是空的,所以 t.name 返回 null,这是导致问题的原因

我尝试了 if else 语句和 try 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 为 null,我不希望其上方的行和文本显示

最佳答案

您可以为此使用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 的元素都从列表中排除,并且当只有null 时不构建Row > 元素。

关于flutter - NoSuchMethodError : The method 'map' was called on null 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57540297/

相关文章:

flutter - Flutter根据引用 list 订购 list

flutter - 在 Release模式下运行 flutter 应用程序时的空白屏幕

flutter - 无法从静态方法dart访问实例成员

firebase - 仅获取 FireBase 集合中 ID 与单独集合中的文档匹配的文档

flutter - 如何解决 List<dynamic> is not a subtype of type 'Map<String, dynamic>?

flutter - 如何在firestore flutter中上传自定义数据模型

dart - 使用 Dart 在 angular2 中进行路由

flutter - 使用选项卡在 flutter 中导航屏幕

flutter - 如何在前台接收推送通知时显示 flutter 本地通知?

flutter - 如何在Flutter中使用动态全局列表