【问题标题】:How to return part of a list of Widgets in Flutter如何在 Flutter 中返回部分 Widget 列表
【发布时间】:2019-04-28 15:52:59
【问题描述】:

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

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 flutter flutter-layout


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您添加这个 - 传播运算符绝对是现在要走的路:)
    【解决方案2】:

    您可以从部分函数返回数组,然后展平整个列表。 How to flatten an array?

    【讨论】:

    • 这是 Dart 2.2.2 的传播运算符之前的最佳答案。感谢您的帮助!
    【解决方案3】:

    是的,有一个模式,你可以建立一个模型类。

    创建一个新文件 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 显示 PostModel 列表 .

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

    阅读更多关于使用 listView.Builder here

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

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 1970-01-01
      • 2019-07-08
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2021-08-12
      • 1970-01-01
      相关资源
      最近更新 更多