Lists are an integral part of mobile applications. Being able to present a list of items is therefore an undeniably important thing to know as a mobile developer. In this article, I will provide various code recipes for implementing ListView in your Flutter applications. Let's get started.
Can be used when you have a predefined list of data that you want to display as well as render some widgets before the list of items and/or after the list of items is displayed.
This creates a list, where you can specify a divider widget to render between list items
class SimpleSeparatedList extends StatelessWidget {
final List<String> items = [
"List item 1",
"List item 2",
"List item 3",
"List item 4",
"List item 5",
];
@override
Widget build(BuildContext context) {
return ListView.separated(
itemCount: items.length,
itemBuilder: (context, index) => ListTile(
title: Text(items[index]),
),
separatorBuilder: (context,index)=>Divider(),
);
}
}
5. Prevent ListView from expanding to fill the area#
You can do this by providing the shrinkwrap property to true. Once the shrinkWrap is set to true, the ListView only takes the space required by it to layout all the children.
class SimpleSeparatedList extends StatelessWidget {
Many times we would like to display a ListView with a fixed header and/or footer. For this we can wrap expanded ListView by a Column widget and add header and footer as we require as follows.
class ListWithHeaderFooter extends StatelessWidget {
final List<String> items = [
"List item 1",
"List item 2",
"List item 3",
"List item 4",
"List item 5",
];
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
child: Text("This is header"),
),
Expanded(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) => ListTile(
title: Text(items[index]),
),
),
),
Container(
child: Text("This is Footer"),
),
],
);
}
}
More over,
You can set scrollDirection property to Axis.horizontal to make a horizontal list view
You can set reverse property to true to change the scroll behavior, in opposite direction (end of the list to the begining)