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

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

问题描述

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

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中返回部分小部件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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