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?
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'),
]
)
You could return arrays from your section functions and then flatten the whole list. How to flatten an array?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With