如何 return Flutter 中 Widget 列表的一部分

How to return part of a list of Widgets in Flutter

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

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 中是否有执行此操作的模式?

您可以 return 来自您的部分函数的数组,然后展平整个列表。 How to flatten an array?

是的,有规律,可以建立模型class。

创建一个新文件post_model.dart

import 'package:flutter/material.dart';

class PostModel {
Widget sectionHeader;
List<Widget> widgetList;

PostModel(Widget this.sectionHeader, List<Widget> this.widgetList);
}

他们将使用 ListView.builder 显示 PostModels 列表 .

body: new ListView.builder
  (
    itemCount: postModelList.length,
    itemBuilder: (BuildContext ctxt, int index) {
     return ....
    }
  )

阅读有关使用 listView.Builder here 的更多信息。

P.S。聪明的方法是将您的帖子编码为 JSON,然后使用 json.decode,here 是如何在项目中使用 json.decode 的示例。

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

ListView(
  children: <Widget>[
    Text('Section 1 Header'),
    ..._buildSection1ListItems(),
    Text('Section 2 Header'),
  ]
)