这可能为时已晚,但所有这些解决方案都不适用于某些场景,例如玩 PopupMenuItems 或影响 UI 渲染!
空安全更新
[
.
.
.
if(condition)...[//Conditionally widget(s) here
Something(...),
],
.
.
.
],
解决方案是在传递给渲染组件之前删除空项:
Column(
children: [
Text('Title'),
name != ''
? Text(name) //show name
: null // just pass a null we will filter it in next line!
].where((e) => e != null).toList()// Filter list and make it List again!
)
这样,我们可以有很多空,UI不会被任何空的Widget影响。
PopupMenuButton 示例我们无法通过 SizedBox:
PopupMenuButton(
icon: Icon(Icons.add),
itemBuilder: (context) => [
PopupMenuItem(
child: Row(children:[ Icon(Icons.folder), Text('So something')]),
value: 'do.something',
),
1 > 2 //⚠️ A false condition
? PopupMenuItem(
child: Row(children: [ Icon(Icons.file_upload), Text('⚠️No way to display ?')]),
'no.way.to.display',
)
: null,// ⚠️ Passing null
PopupMenuItem(
child: Row(children: [ Icon(Icons.file_upload), Text('Do something else')]),
'do.something.else',
)
].where((e) => e != null).toList(),//ℹ️ Removing null items
onSelected: (item) {}
)
这可以用作extension的API:
extension NotNulls on List {
///Returns items that are not null, for UI Widgets/PopupMenuItems etc.
notNulls() {
return where((e) => e != null).toList();
}
}
//Usage:
PopupMenuButton(
icon: Icon(Icons.add),
itemBuilder: (context) => [
PopupMenuItem(
child: Row(children:[ Icon(Icons.folder), Text('So something')]),
value: 'do.something',
),
1 > 2 //⚠️ A false condition
? PopupMenuItem(
child: Row(children: [ Icon(Icons.file_upload), Text('⚠️No way to display ?')]),
'no.way.to.display',
)
: null,// ⚠️ Passing null
PopupMenuItem(
child: Row(children: [ Icon(Icons.file_upload), Text('Do something else')]),
'do.something.else',
)
].notNulls(),//ℹ️ Removing null items
onSelected: (item) {}
)