如何在 Flutter 中返回部分小部件列表

Cra*_*enz 7 dart flutter flutter-layout

我有一个由多个部分组成的页面,每个部分由一个标题和文本列表组成。我希望整个系列作为一个系列均匀滚动,并且想知道如何最好地分解这种逻辑。想象一下下面的小部件树:

ListView(
  children: <Widget>[
    Text('Section 1 Header'),
    Text('Section 1 List Item 1'),
    Text('Section 1 List Item 2'),
    Text('Section 2 Header'),
    ...
  ]
)
Run Code Online (Sandbox Code Playgroud)

就可以干净地构建它的辅助函数而言,类似以下的内容会很好:

ListView(
  children: <Widget>[
    Text('Section 1 Header'),
    _buildSection1ListItems(),
    Text('Section 2 Header'),
  ]
)
Run Code Online (Sandbox Code Playgroud)

_buildSection1ListItems()如下所示:

List<Widget> _buildSection1ListItems() {
  return [
    Text('Section 1 List Item 1'),
    Text('Section 1 List Item 2'),
  ];
}
Run Code Online (Sandbox Code Playgroud)

并且不喜欢以下内容:

Widget _buildSection1ListItems() {
  return Expanded(
    child: Column(
      children: <Widget>[
        Text('Section 1 List Item 1'),
        Text('Section 1 List Item 2'),
      ]
    )
  );
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我所想出的只是明显的第二个解决方案,但它引入了许多纯粹受业务逻辑重构细节影响的琐碎小部件,而不是用于显示内容的实际、理想的小部件树。

在 Flutter 中是否有这样做的模式?

小智 10

在 Dart 2.2.2 或更高版本中,您可以使用扩展运算符:

ListView(
  children: <Widget>[
    Text('Section 1 Header'),
    ..._buildSection1ListItems(),
    Text('Section 2 Header'),
  ]
)
Run Code Online (Sandbox Code Playgroud)