Flutternull安全条件小部件
在 Flutter 引入空安全功能之前,我能够有条件地在列表中添加小部件,如下所示:
actions: <Widget>[
canCancel
? CupertinoDialogAction(
child: Text(cancelActionText),
onPressed: () {
Navigator.pop(context);
},
)
: null,
].where(notNull).toList()
notNull 是一个自制的过滤器,可以过滤掉空对象......
现在有了空安全,这是不可能的,因为小部件列表必须严格为非空。什么是更好的方法?
回答
只需if在List:
<Widget>[
if (true) Widget(),
]
您的代码示例:
actions: <Widget>[
if (canCancel)
CupertinoDialogAction(
child: Text(cancelActionText),
onPressed: () {
Navigator.pop(context);
},
),
]