dart - 如何在 Flutter 中返回部分 Widget 列表
问题描述
我有一个由多个部分组成的页面,每个部分都包含一个标题和文本列表。我希望整个系列作为一个系列统一滚动,并且想知道如何最好地分解这种逻辑。想象一下下面的小部件树:
ListView(
children: <Widget>[
Text('Section 1 Header'),
Text('Section 1 List Item 1'),
Text('Section 1 List Item 2'),
Text('Section 2 Header'),
...
]
)
就干净地构建它的辅助函数而言,类似以下的东西会很好:
ListView(
children: <Widget>[
Text('Section 1 Header'),
_buildSection1ListItems(),
Text('Section 2 Header'),
]
)
如下_buildSection1ListItems()
所示:
List<Widget> _buildSection1ListItems() {
return [
Text('Section 1 List Item 1'),
Text('Section 1 List Item 2'),
];
}
并且不喜欢以下内容:
Widget _buildSection1ListItems() {
return Expanded(
child: Column(
children: <Widget>[
Text('Section 1 List Item 1'),
Text('Section 1 List Item 2'),
]
)
);
}
到目前为止,我所想出的只是明显的第二种解决方案,但它引入了许多纯粹受业务逻辑重构细节影响的无聊小部件,而不是用于显示内容的实际、理想的小部件树。
在 Flutter 中有这样做的模式吗?
解决方案
在 Dart 2.2.2 或更高版本中,您可以使用扩展运算符:
ListView(
children: <Widget>[
Text('Section 1 Header'),
..._buildSection1ListItems(),
Text('Section 2 Header'),
]
)
推荐阅读
- python - 如何从 pandas 数据框中另一列的多个值创建列中的值列表?
- javascript - 通过包含的单词获取元素
- python - 忽略 tensorflow.python 中未解析的引用
- python - 如何从 Python 运行 SQL Server 脚本
- java - 用 Jackson 序列化 ImmutableMap
- mysql - 为什么当我们使用 python pandas 插入时,mysql varchar 列将 .0 附加到 phonenumer
- ios - Xcode 12 - 当有另一个 Swift 包作为依赖项时,SwiftUI 预览在 Swift 包上不起作用 - 向代理发送“previewInstances”消息
- windows - Windows 驱动程序 - HCK 签名不工作 8/8.1/2012
- git - VIM - coc.vim:没有这样的文件或目录
- python - VSCode:Jupyter 不会导出为 Python 脚本