I currently have a ListView that displays cards that have several properties and it’s being displayed properly within an expanded widget:
return Expanded(
child: renderCardsList(docs, homeState),
);
Each of these cards have dates and I want to split the list by the current date (to have something like past/upcoming), but I’m having issues displaying 2 ListViews with text in between.
For example, ideally I’d like something like this:
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: [
Text('Upcoming'),
renderCardsList(docs1, homeState),
Text('Past'),
renderCardsList(docs2, homeState),
],
),
),
With the entire list being scrollable. I’ve tried several combinations of adding Expanded widgets, switching columns up, etc with no luck.
Any help is much appreciated, thanks!
Code for renderCardsList
ListView renderCardsList(dynamic list, dynamic state) {
ListView result = ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
DocumentSnapshot? snapshot = list[index];
if (snapshot != null) {
var snapshotData = snapshot.data() as Map<String, dynamic>
Object obj = Object(
id: key,
name: snapshotData['name'],
date: snapshotData[‘date’],
);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
child: Card(
data: obj,
);
}
}
return const SizedBox.shrink();
},
);
return result;
}
2
Answers
Update: I didn't figure this out for a ListView but I was able to rewrite my renderCardsList function to return List instead and return those cards through that.
Then you can use them just like this.
This works for me for now as it's not a large list but would be curious if anyone has a way to use the ListView as I believe it's much more performant for long lists.
You are encountering an issue with the
SingleChildScrollView
that containsListView
s.A
ListView
will attempt to take as much space as possible for its axis. In your case, the vertical axis. However, the vertical axis is unbounded, because aSingleChildScrollView
has an infinite height.The solution is simply to tell your
ListView
s to only take up as much space as possible:Without
shrinkWrap
being set totrue
, the framework will not be able to lay out your list views in an unbounded vertical axis.I created mock data and put multiple
ListView
s inside aColumn
, inside aSingleChildScrollView
:Output using
shrinkWrap
:Here is the full example code: