We're hiring
Products

Channels

Beams

Chatkit

DocsTutorialsSupportCareersPusher Blog
Sign InSign Up
Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing
Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing
Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Sign InSign Up

Mastering Flutter ListViews

  • Suragch
January 30th, 2019
You will need Dart and Flutter set up on your system.

Introduction

If you have done any Android or iOS development before, you are going to love how easy it is to make ListViews in Flutter. In this article we will use simple examples to look at all of the common use cases for making them. Consider this page a reference. Bookmark it and come back here to copy-and-paste the code snippets as starters in your own projects.

First we will look at the main types of ListViews that are available. After that I'll show you how to style the items. Finally I'll cover how to make changes by adding and removing items in the list.

Prerequisites

I'm assuming that you have the Flutter development environment set up and that you have a basic knowledge of how to make an app. If not, check out the following links:

I'm using Android Studio with Flutter 1.0 for this article, but you should be fine if you are using another IDE.

Setup

Start a new Flutter project. I'm calling mine flutter_listview.

Open main.dart and replace the code with the following:

    import 'package:flutter/material.dart';

    void main() => runApp(MyApp());

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'ListViews',
          theme: ThemeData(
            primarySwatch: Colors.teal,
          ),
          home: Scaffold(
            appBar: AppBar(title: Text('ListViews')),
            body: BodyLayout(),
          ),
        );
      }
    }

    class BodyLayout extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return _myListView(context);
      }
    }

    // replace this function with the code in the examples
    Widget _myListView(BuildContext context) {
      return ListView();
    }

Note the _myListView() function at the end. You will be replacing this with the code in the examples below.

Basic types of ListViews

Static ListView

If you have a short list of items that don't change, then you can use the default ListView constructor to make it. This is useful for making something like a settings menu page.

Replace _myListView() with the following:

    Widget _myListView(BuildContext context) {
      return ListView(
        children: <Widget>[
          ListTile(
            title: Text('Sun'),
          ),
          ListTile(
            title: Text('Moon'),
          ),
          ListTile(
            title: Text('Star'),
          ),
        ],
      );
    }

Run the app and you should see the following image. (After this when refreshing, usually hot reload works fine, but I find at times I need to do a hot restart or even completely stop and restart the app.)

Look back at the code. The children of the ListView were ListTiles. A ListTile is a special widget that is preconfigured to handle the most common layouts that you would want in a ListView. Our list above only included a title, but a ListTile can also include subtitles, icons, and images. We will come back to ListTiles when we look at styling below.

If you want to add dividers between the rows then use the ListTile.divideTiles constructor.

    Widget _myListView(BuildContext context) {
      return ListView(
        children: ListTile.divideTiles(
          context: context,
          tiles: [
            ListTile(
              title: Text('Sun'),
            ),
            ListTile(
              title: Text('Moon'),
            ),
            ListTile(
              title: Text('Star'),
            ),
          ],
        ).toList(),
      );
    }

The lines are faint, but look carefully:

Dynamic ListView

All of the elements of a static ListView get created at once. This is fine for a short list but not for a long list. You can make a dynamically created ListView by using the ListView.builder() constructor. This will create the ListView items only when they need to be displayed on the screen. It works like an Android RecyclerView but is a lot easier to set up.

Replace _myListView() with the following:

    Widget _myListView(BuildContext context) {

      // backing data
      final europeanCountries = ['Albania', 'Andorra', 'Armenia', 'Austria', 
        'Azerbaijan', 'Belarus', 'Belgium', 'Bosnia and Herzegovina', 'Bulgaria',
        'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland',
        'France', 'Georgia', 'Germany', 'Greece', 'Hungary', 'Iceland', 'Ireland',
        'Italy', 'Kazakhstan', 'Kosovo', 'Latvia', 'Liechtenstein', 'Lithuania',
        'Luxembourg', 'Macedonia', 'Malta', 'Moldova', 'Monaco', 'Montenegro',
        'Netherlands', 'Norway', 'Poland', 'Portugal', 'Romania', 'Russia',
        'San Marino', 'Serbia', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 
        'Switzerland', 'Turkey', 'Ukraine', 'United Kingdom', 'Vatican City'];

      return ListView.builder(
        itemCount: europeanCountries.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(europeanCountries[index]),
          );
        },
      );

    }

Which gives:

Look back at the code. I provided an itemCount that tells the ListView how many list items there will be. I also provided an itemBuilder function that dynamically builds each ListTile as it comes into view. The function provides the BuildContext as the context parameter and the item position as the index parameter. The index makes it convenient to get the data items from the list of European country names that we are using as the backing data.

Infinite list

I remember struggling trying to make infinite lists in the past with Android or iOS. Flutter makes it simple, though. Just remove the itemCount parameter from the ListView.builder constructor. Since Europe doesn't have an infinite number of countries, we'll change the ListTile to display the row index.

Replace _myListView() with the following:

    Widget _myListView(BuildContext context) {
      return ListView.builder(
        itemBuilder: (context, index) {
          return ListTile(
            title: Text('row $index'),
          );
        },
      );
    }

Which gives:

You can scroll all day and you'll never get to the end. That was way too easy. I love it.

If you want to add dividers between tiles in a dynamic ListView, you can use the ListView.separated constructor.

    Widget _myListView(BuildContext context) {
      return ListView.separated(
        itemCount: 1000,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text('row $index'),
          );
        },
        separatorBuilder: (context, index) {
          return Divider();
        },
      );
    }

Again, you have to look carefully to see the dividers. You can add arguments to Divider() if you want to change the line height or color.

Horizontal ListView

It's also really easy to make a horizontally scrolling ListView. All you have to do is specify the scrollDirection as horizontal. Since ListTiles aren't designed for horizontal ListViews, we will use a simple custom layout.

Replace _myListView() with the following:

    Widget _myListView(BuildContext context) {
      return ListView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          return Container(
            margin: const EdgeInsets.symmetric(horizontal: 1.0),
            color: Colors.tealAccent,
            child: Text('$index'),
          );
        },
      );
    }

Which gives:

Styling

We’ve covered the main ListView types above, but they were pretty plain. Flutter offers a lot of options to make them more beautiful.

ListTile customization

The Flutter team designed the ListTile widget to handle the normal content that you would want in a list. This means that most of the time there is no need to define a custom layout. You can just use the default ListTile for each item in the list. When we made a ListView in the example above we only used the title option. But we can also show subtitles, images, and icons.

Replace _myListView() with the following:

    Widget _myListView(BuildContext context) {
      return ListView(
        children: <Widget>[
          ListTile(
            leading: Icon(Icons.wb_sunny),
            title: Text('Sun'),
          ),
          ListTile(
            leading: Icon(Icons.brightness_3),
            title: Text('Moon'),
          ),
          ListTile(
            leading: Icon(Icons.star),
            title: Text('Star'),
          ),
        ],
      );
    }

The leading is for adding an icon or image at the start of the ListTile.

You can also add an icon at the end if you specify the trailing attribute.

    ListTile(
      leading: Icon(Icons.wb_sunny),
      title: Text('Sun'),
      trailing: Icon(Icons.keyboard_arrow_right),
    ),

The right arrow icon makes it look like the list items are clickable, but they aren't. Not yet. We will see how to add touch events in the next section. It's easy. (Hint: onTap )

Instead of icons, we can also use images. The recommended image option is to use a CircleAvatar widget.

Replace _myListView() with the following:

    Widget _myListView(BuildContext context) {
      return ListView(
        children: <Widget>[
          ListTile(
            leading: CircleAvatar(
              backgroundImage: AssetImage('assets/sun.jpg'),
            ),
            title: Text('Sun'),
          ),
          ListTile(
            leading: CircleAvatar(
              backgroundImage: AssetImage('assets/moon.jpg'),
            ),
            title: Text('Moon'),
          ),
          ListTile(
            leading: CircleAvatar(
              backgroundImage: AssetImage('assets/stars.jpg'),
            ),
            title: Text('Star'),
          ),
        ],
      );
    }

It won’t work yet because we need to add the images.

You could have used NetworkImage(imageUrl) instead of AssetImage(path). I chose AssetImage, though, so that everything is self-contained here. Create an assets folder in the project’s root directory and add the following images to it:

In pubspec.yaml register the assets location:

    flutter:
      assets:
        - assets/

If you haven't done this before and are running into problems, you can check out this post for more help.

Do a full restart (stop and start) of the app. This gives us the following:

Before we leave ListTile customization, one last thing we should cover is subtitles. Edit the code above to add a subtitle argument.

    ListTile(
      leading: CircleAvatar(
        backgroundImage: AssetImage('assets/sun.jpg'),
      ),
      title: Text('Sun'),
      subtitle: Text('93 million miles away'), //           <-- subtitle
    ),

As you can see, the subtitle adds a line of smaller text below the title.

Cards

Cards are a great way to make your list look classy. All you have to do is wrap your ListTile with a Card widget.

Replace _myListView() with the following:

    Widget _myListView(BuildContext context) {

      final titles = ['bike', 'boat', 'bus', 'car',
      'railway', 'run', 'subway', 'transit', 'walk'];

      final icons = [Icons.directions_bike, Icons.directions_boat,
      Icons.directions_bus, Icons.directions_car, Icons.directions_railway,
      Icons.directions_run, Icons.directions_subway, Icons.directions_transit,
      Icons.directions_walk];

      return ListView.builder(
        itemCount: titles.length,
        itemBuilder: (context, index) {
          return Card( //                           <-- Card widget
            child: ListTile(
              leading: Icon(icons[index]),
              title: Text(titles[index]),
            ),
          );
        },
      );
    }

Which gives:

Play around with the Card attributes. You can change the shadow by adjusting the elevation. Also try changing the shape and margin.

Custom list item

If a ListTile doesn't fit your needs, you are free to design your own tile. Remember, all that ListView wants is a list of widgets. Any widget is fine. I recently worked on an app that required multiple columns in each list item. Here is a simplified example.

    Widget _myListView(BuildContext context) {

      // the Expanded widget lets the columns share the space
      Widget column = Expanded(
        child: Column(
          // align the text to the left instead of centered
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('Title', style: TextStyle(fontSize: 16),),
            Text('subtitle'),
          ],
        ),
      );

      return ListView.builder(
        itemBuilder: (context, index) {
          return Card(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                children: <Widget>[
                  column,
                  column,
                ],
              ),
            ),
          );
        },
      );

    }

Touch detection

If you are using a ListTile, all you have to do to respond to user touch is to add an onTap or onLongTouch callback.

Replace _myListView() with the following:

    Widget _myListView(BuildContext context) {
      return ListView(
        children: <Widget>[
          ListTile(
            title: Text('Sun'),
            trailing: Icon(Icons.keyboard_arrow_right),
            onTap: () {
              print('Sun');
            },
          ),
          ListTile(
            title: Text('Moon'),
            trailing: Icon(Icons.keyboard_arrow_right),
            onTap: () {
              print('Moon');
            },
          ),
          ListTile(
            title: Text('Star'),
            trailing: Icon(Icons.keyboard_arrow_right),
            onTap: () {
              print('Star');
            },
          ),
        ],
      );
    }

Setting the onTap parameter allows us to respond when the row is clicked. Here we are just printing a string. (Make sure the Run tab is selected in Android Studio to see the print output.)

In a more realistic situation we would probably navigate to a new screen (see Responding to user input) or show a detail view on a tablet.

If you are working with a custom list item layout instead of a ListTile, you can just wrap your widget in an InkWell. Let’s modify our custom two-column row from above:

      return ListView.builder(
        itemBuilder: (context, index) {
          return Card(
            child: InkWell(
              onTap: () {
                print('tapped');
              },
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: <Widget>[
                    column,
                    column,
                  ],
                ),
              ),
            ),
          );
        },
      );

Of course there are other options, too. We could wrap each column separately in an InkWell or add a button or some other gesture detector.

Updating list data

Adding and deleting rows in a ListView

It is pretty easy to update the items in a normal ListView. All you have to do is use a Stateful widget and call setState() whenever the row data changes.

Since we need a Stateful widget, replace both BodyLayout and _myListView() with the following code:

    class BodyLayout extends StatefulWidget {
      @override
      BodyLayoutState createState() {
        return new BodyLayoutState();
      }
    }

    class BodyLayoutState extends State<BodyLayout> {

      List<String> titles = ['Sun', 'Moon', 'Star'];

      @override
      Widget build(BuildContext context) {
        return _myListView();
      }

      Widget _myListView() {
        return ListView.builder(
          itemCount: titles.length,
          itemBuilder: (context, index) {
            final item = titles[index];
            return Card(
              child: ListTile(
                title: Text(item),

                onTap: () { //                                  <-- onTap
                  setState(() {
                    titles.insert(index, 'Planet');
                  });
                },

                onLongPress: () { //                            <-- onLongPress
                  setState(() {
                    titles.removeAt(index);
                  });
                },

              ),
            );
          },
        );
      }
    }

When you tap an item it adds a "Planet" item at that index. When you long press an item, it removes it.

The problem with this method, though, is that the changes are abrupt. To make adding and deleting rows look nicer, Flutter has an AnimatedList widget.

Adding and deleting rows in an AnimatedList

Replace the BodyLayoutState class with the following code:

    class BodyLayoutState extends State<BodyLayout> {

      // The GlobalKey keeps track of the visible state of the list items
      // while they are being animated.
      final GlobalKey<AnimatedListState> _listKey = GlobalKey();

      // backing data
      List<String> _data = ['Sun', 'Moon', 'Star'];

      @override
      Widget build(BuildContext context) {
        return Column(
          children: <Widget>[
            SizedBox(
              height: 300,
              child: AnimatedList(
                // Give the Animated list the global key
                key: _listKey,
                initialItemCount: _data.length,
                // Similar to ListView itemBuilder, but AnimatedList has
                // an additional animation parameter.
                itemBuilder: (context, index, animation) {
                  // Breaking the row widget out as a method so that we can
                  // share it with the _removeSingleItem() method.
                  return _buildItem(_data[index], animation);
                },
              ),
            ),
            RaisedButton(
              child: Text('Insert item', style: TextStyle(fontSize: 20)),
              onPressed: () {
                _insertSingleItem();
              },
            ),
            RaisedButton(
              child: Text('Remove item', style: TextStyle(fontSize: 20)),
              onPressed: () {
                _removeSingleItem();
              },
            )
          ],
        );
      }

      // This is the animated row with the Card.
      Widget _buildItem(String item, Animation animation) {
        return SizeTransition(
          sizeFactor: animation,
          child: Card(
            child: ListTile(
              title: Text(
                item,
                style: TextStyle(fontSize: 20),
              ),
            ),
          ),
        );
      }

      void _insertSingleItem() {
        String newItem = "Planet";
        // Arbitrary location for demonstration purposes
        int insertIndex = 2;
        // Add the item to the data list.
        _data.insert(insertIndex, newItem);
        // Add the item visually to the AnimatedList.
        _listKey.currentState.insertItem(insertIndex);
      }

      void _removeSingleItem() {
        int removeIndex = 2;
        // Remove item from data list but keep copy to give to the animation.
        String removedItem = _data.removeAt(removeIndex);
        // This builder is just for showing the row while it is still
        // animating away. The item is already gone from the data list.
        AnimatedListRemovedItemBuilder builder = (context, animation) {
          return _buildItem(removedItem, animation);
        };
        // Remove the item visually from the AnimatedList.
        _listKey.currentState.removeItem(removeIndex, builder);
      }
    }

This is the result:

Read through the comments that I added to the code above. Here are some important points about AnimatedLists:

  • An AnimatedList needs a GlobalKey that keeps track of the widgets while they are being animated. Every time you make a change to the list, you need to update both the backing data list and the global key.
  • Our row widgets are stateless, but if your rows have state, then you will need a key for them, too. This helps the system know when a change actually happens. See this video from the Flutter team for more about that.
  • I used a SizedTransition as the animation here, but see the documentation for other options.

Conclusion

We have taken a full tour of ListViews. You should have a solid understanding now of how to implement the vast majority of use cases that you will encounter. Check out the Further Study section below to see ListViews being used in more advanced situations.

The source code for this tutorial is available on GitHub.

Further study

Clone the project repository
  • Android
  • Flutter
  • iOS
  • no pusher tech

Products

  • Channels
  • Beams
  • Chatkit

© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.