集合控制流¶
这是 Dart 的集合控制流(collection if)配合展开操作符(...)的写法。意思是:
- 在一个列表字面量(例如
children: [...])内部,写if (_showTopInfo) ...[widgetA, widgetB]会在_showTopInfo为true时把widgetA和widgetB展开并插入到父列表中; - 如果条件为
false,这两个元素不会被插入。 - 适用于需要有条件地插入多于一个 widget 的场景。如果只插入单个 widget,可直接写
if (_showTopInfo) widgetA,(不需要...)。
示例代码说明(用于 children 中条件性插入多个子项):
Widget build(BuildContext context) {
bool show = true;
return Column(
children: [
Text('固定项'),
// 当 show 为 true 时,将下面两个 Widget 展开并插入到 children 列表中
if (show) ...[
Container(color: Colors.blue, height: 40),
Divider(),
],
Text('其它项'),
],
);
}