Lists are incredibly important when working on mobile. It’s a key part of both iOS and Android SDKs. Naturally, the same is true with Flutter.
Now in the old days of both iOS and Android, it took quite a bit of code to create a list. They often required the developer create several specialized classes.
With SwiftUI and Jetpack Compose, lists went from a complex machine requiring a variety of components to simple constructs often times resembling a for loop. Flutter, being declarative in nature, is no different.
In this episode, we’ll create a simple list from the ListView widget. The listView is quite configurable for a variety of situations. You simply pass the children in an array, and the list view will display them. In our case, we want to dynamically create our list. For this, the ListView has three important properties: padding, an item count and an item builder.
Padding allows you to add padding surrounding the children in the list. You can pass EdgeInsets to add the padding.
The item count lets the ListView know how many children are contained in it.
Finally, the itemBuilder is called for each item. It is passed in with a context and a position on the list. Using these two properties, you can get the position in the list and then return a widget to display in the list. Okay let’s dive into it.
Open your project in progress or download the starter project for this episode. We’ll create a ListView for our courses page. Open the courses_page.dart in the courses subfolder found in the ui folder.
In _CoursesPageState, we’ll get started by creating a helper method that creates the widget for a row in the list.
Widget _buildRow(Course course) {
return Text(course.name);
}
Okay, that’s the row. Now it’s time to create the actual list view. We’ll replace the Text widget with the ListView widget.
return ListView.builder(
);
First, we’ll add some padding. We’ll set the padding to 16 all the way around.
padding: const EdgeInsets.all(16.0),
Next, we’ll set the item count which is the length of the courses.
itemCount: courses.length,
Now for the item builder. We get the context and position. We’ll get the current course based on the position and pass it into our buildRow method.
itemBuilder: (BuildContext context, int position) {
return _buildRow(courses[position]);
},
Believe it or not, that’s all we need to do to get our ListView up and running. Now build and run or hot reload. Now we have a nice looking list of titles for our courses. Mind you, the formatting is lacking but we’ll spend the rest of this part making this list look good.