如何在 Flutter 中返回部分 Widget 列表 [英] How to return part of a list of Widgets in Flutter

查看:76
本文介绍了如何在 Flutter 中返回部分 Widget 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a page comprised of multiple sections, each consisting of a header and list of text. I would like the whole collection to scroll uniformly, as one series, and am wondering how best to break apart this logic. Imagine the following tree of widgets:

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

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

In terms of helper functions that build this cleanly, something like the following would be nice:

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'),
      ]
    )
  );
}

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

All I've figured out so far is that obvious second solution, but it introduces so many frivolous widgets influenced purely by business logic refactoring niceties, and not the actual, ideal tree of widgets to display content.

在 Flutter 中有这样的模式吗?

Is there a pattern for doing this in Flutter?

推荐答案

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

As Dart 2.2.2 or later, you can use the spread operator:

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

这篇关于如何在 Flutter 中返回部分 Widget 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆