有时 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/