Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return part of a list of Widgets in 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'),
  ]
)

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?

like image 793
Craig Labenz Avatar asked Nov 26 '18 23:11

Craig Labenz


3 Answers

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'),
  ]
)
like image 127
Son Chau Avatar answered Jan 03 '23 09:01

Son Chau


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

like image 29
Chris Reynolds Avatar answered Jan 03 '23 08:01

Chris Reynolds


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.

like image 41
Allex Radu Avatar answered Jan 03 '23 09:01

Allex Radu