Starting With Flutter: Lists

Are you willing to start developing in Flutter but you don’t even know how to set up a list of elements? Well fear not! I’ve come to show you how to create a simple list of items in Flutter. For free!!!

I imagine you’re already familiar with Flutter, Dart and declarative programming, if not, you should go through these tutorials first.

We’ll be focusing on creating a custom list with an array of custom items, because it may be the most common situation to address with list. Also we won’t see scaffolds creation or any other starting point.

1. Create data structure

First things first, let’s create a data structure and a list of objects. I think that a simple “newsfeed” data will be enough for our example:

Simple as that. A unique id, title, content, image and a link to a webpage.

Then we’ll create a simple list of those objects:

Possibly those items would be the payload of a API call.

2. Build the list element

In spite of what you may think you can use any widget as list item so, because ListTile is not really what we want, we can create a new Stateless widget and call it ListElem.

We wish to add the image to the left, on the right the title in bold and 2 lines max of content, so we can create the Stateless Widget that represents it. We also need to add a News item as component for the constructor because the widget needs to know which data render.

3. Add the list to our body

We pretty much have all out elements in order, then we just need to create a list. The ListView widget comes with a “children” parameter which takes an array of widgets. So we can create an array of LIstElem and give it to the ListView.

Another way to create a ListView is by using a builder which is a bit more similar on how Android creates lists. You’ll need to know the number of items (e.g. the lenght of the array) and with the itemBuilder all the items will be created by the framework:

This last one is a way cleaner method to generate a list and is the one that I suggest you to use.

Still with both ways we’ll obtain the same result:

There you are. You can customize your list items as you wish because ListView just needs an array of widgets so you can easily create way more complex layouts and also mix different list items.