How to return part of a list of Widgets in Flutter

无人久伴 提交于 2020-02-22 05:38:05

问题


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

Where _buildSection1ListItems() looks like the following:

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

And NOT like the following:

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.

Is there a pattern for doing this in Flutter?


回答1:


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



回答2:


You could return arrays from your section functions and then flatten the whole list. How to flatten an array?




回答3:


Yes, there is a pattern, you can build a model class.

make a new file post_model.dart

import 'package:flutter/material.dart';

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

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

Them you're going to display a list of PostModels using a ListView.builder .

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

Read more about using a listView.Builder here.

P.S. The smart way is to encode your posts as JSON, then use json.decode, here's an example how to use json.decode in a project.



来源:https://stackoverflow.com/questions/53490661/how-to-return-part-of-a-list-of-widgets-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!