Flutter ListView

Flutter ListView Tutorial and Examples.

In this tutorial we want to look at one of the most important widgets especially when it comes to rendering lists of data, the ListView.

What is a ListView?

A ListView is a scrollable list of widgets arranged linearly.

As the names suggests it’s responsibility is list items. These items can then scrolled. ListView isn’t the only scrolling view. There are others like gridview, however ListView is the most commonly used.

ListView will display its children one after another in the scroll direction. In the cross axis, the children are required to fill the ListView.

Here’s a simple infinite listview:

new ListView.builder(
  padding: new EdgeInsets.all(8.0),
  itemExtent: 20.0,
  itemBuilder: (BuildContext context, int index) {
    return new Text('entry $index');
  },
)

More ListView documentation can be found here.

Let’s look a flutter ListView example with onClick.

Why ListView?

Well ListViews are probably the most commonly used widgets for displaying lists of data. In most cases we use it together with CardViews. And in fact render images and text. You may have already seen countless apps with lists of images and text.

If it is flutter application, then chances are that either gridview or listview has been used.

ListViews and GridViews are important because given the nature(small screen) of mobile devices, you always need to have the ability to scroll through data. The screen can only display a small of data per viewport. So we need a component that can easily be scrolled.

Also the fact that most of mobile apps by their nature require the ability to show lists of data. Mobile apps are not mostly used for heavy data entry like Microsoft Word, Excel etc in PC. Rather majority of apps require us to fetch data from the server and render to the user. These types of apps need widgets like ListViews.

1. Flutter Simple ListView with OnClick Example

This is a simple flutter listview example to display items from a flutter fixed-length list, otherwise known as an array in other languages. Obviously we write our app in Dart programming language.

Flutter ListView

Flutter ListView

 

If the user clicks a single cardview, a CupertinoAlertDialog will be rendered with the clicked item.

The dialog will have some text and icon.

And here’s our video tutorial:

Here are the files we explore:

  1. pubspec.yaml
  2. lib/main.dart
(a). pubspec.yaml
name: simple_listview
description: A Simple ListView Flutter application.

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter
flutter:
  uses-material-design: true
(b). main.dart

This is where we write our flutter code in dart programming language. In Dart it is very common to write several classes in a single file. So this simple file will have three classes.

Importing Packages in Flutter/Dart

But first we need to import some packages and we do that using the import keyword in dart.

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

Here are the packages we are importing:

  1. material.dart : will give us material design widgets and theme.
  2. cupertino.dart : Will give us CupertinoAlertDialog as well as cupertino icons.
Creating classes in Flutter/Dart

In Dart like in most C style programming languages you create a class using the class keyword. Classes are encapsulation mechanism in Object Oriented Programming languages.

In this case we create three classes:
1.class MyApp extends StatelessWidget {..}

  1. class Home extends StatefulWidget {..}
  2. class _HomeState extends State<Home> {..}

Our first class is deriving from StatelessWidget and implementing the build() method. That method will build a materialapp widget with title, home and theme set and return it as a widget.

The second class will derive from StatefulWidget and override the createState() method.

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter ListView',
      home: new Home(),
      theme: new ThemeData(primaryColor: Colors.orange),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => new _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {
    var spacecrafts = ["James Web","Enterprise","Hubble","Kepler","Juno","Casini","Columbia","Challenger","Huygens","Galileo","Apollo","Spitzer","WMAP","Swift","Atlantis"];
    var listItem = new ListView.builder(
      itemCount: spacecrafts.length,
      itemBuilder: (BuildContext context, int index) {
        return new ListTile(
          title: new Card(
            elevation: 5.0,
            child: new Container(
              alignment: Alignment.centerLeft,
              margin: new EdgeInsets.only(top: 10.0, bottom: 10.0),
              child: new Text(spacecrafts[index]),
            ),
          ),
          onTap: () {
            showDialog(
                barrierDismissible: false,
                context: context,
                child: new CupertinoAlertDialog(
                  title: new Column(
                    children: <Widget>[
                      new Text("ListView"),
                      new Icon(
                        Icons.favorite,
                        color: Colors.red,
                      ),
                    ],
                  ),
                  content: new Text( spacecrafts[index]),
                  actions: <Widget>[
                    new FlatButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: new Text("OK"))
                  ],
                ));
          },
        );
      },
    );

    return new Scaffold(
      appBar: new AppBar(
          title: new Text("Flutter ListView")
      ),
      body: listItem,
    );
  }
}
void main() {
  runApp(new MyApp());
}

Flutter ListView with Images and text

Let’s look at a simple example to render images/icons and text in a ListView in ListTiles. This is a very basic example.

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build (BuildContext context){
    final title = 'Basic List';
    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: ListView(
          children: <Widget>[
            ListTile(
              title: Text('Map'),
              leading: Icon(Icons.map),
            ),
            ListTile(
              title: Text('Photo Album'),
              leading: Icon(Icons.photo_album),
            ),
            ListTile(
              title: Text('Phone'),
              leading: Icon(Icons.phone),
            ),
          ],)
      )
    );
  } 
}
Share

3 Examples

  1. Flutter ListView with Material Letter Icons

    You can create a listview similar to one used in many contacts app where the first letter in the name is iconized. This makes the listview look quite beautiful especially if you are not rendering images in the listview.

    Below is a listview example to make that possible without using any third party package.

    (a). contact.dart

    This is the model or data object class. It will represent a single contact.

    class ContactModal {
      final String fullName;
      final String email;
    
      const ContactModal({this.fullName, this.email});
    }
    

    Name and email are the properties of a single contact instance for us.

    (b). contact_list.dart

    This is a simple statelesswidget class to hold a list of contacts for us.

    import 'package:flutter/material.dart';
    import 'package:using_listview/contactlist/contact_list_item.dart';
    import 'package:using_listview/contactlist/modal/contact.dart';
    
    class ContactsList extends StatelessWidget {
      final List<ContactModal> _contactModal;
    
      ContactsList(this._contactModal);
    
      @override
      Widget build(BuildContext context) {
        return new ListView(
          padding: new EdgeInsets.symmetric(vertical: 8.0),
          children: _buildContactsList(),
        );
      }
    
      List<ContactListItem> _buildContactsList() {
        return _contactModal
            .map((contact) => new ContactListItem(contact))
            .toList();
      }
    }
    

     

    (c). contact_list_item.dart

    This is a statelesswidget that we will build and return in form of a ListTile. It will represent a single list item.

    import 'package:flutter/material.dart';
    import 'package:using_listview/contactlist/modal/contact.dart';
    
    class ContactListItem extends StatelessWidget {
      final ContactModal _contactModal;
    
      ContactListItem(this._contactModal);
    
      @override
      Widget build(BuildContext context) {
        return new ListTile(
            leading: new CircleAvatar(child: new Text(_contactModal.fullName[0])),
            title: new Text(_contactModal.fullName),
            subtitle: new Text(_contactModal.email));
      }
    }
    

     

    (d). contact_page.dart

    This is a statelesswidget that will return an array of contact models.

    import 'package:flutter/material.dart';
    import 'package:using_listview/contactlist/contact_list.dart';
    import 'package:using_listview/contactlist/modal/contact.dart';
    
    class ContactPage extends StatelessWidget {
      _buildContactList() {
        return <ContactModal>[
          const ContactModal(
              fullName: 'Romain Hoogmoed', email: 'romain.hoogmoed@example.com'),
          const ContactModal(
              fullName: 'Emilie Olsen', email: 'emilie.olsen@example.com'),
          const ContactModal(
              fullName: 'Nishant Srivastava', email: 'nishant.srivastava@example.com'),
          const ContactModal(
              fullName: 'Romain Hoogmoed', email: 'romain.hoogmoed@example.com'),
          const ContactModal(
              fullName: 'Emilie Olsen', email: 'emilie.olsen@example.com'),
          const ContactModal(
              fullName: 'Nishant Srivastava', email: 'nishant.srivastava@example.com'),
          const ContactModal(
              fullName: 'Romain Hoogmoed', email: 'romain.hoogmoed@example.com'),
          const ContactModal(
              fullName: 'Emilie Olsen', email: 'emilie.olsen@example.com'),
          const ContactModal(
              fullName: 'Nishant Srivastava', email: 'nishant.srivastava@example.com'),
        ];
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(body: new ContactsList(_buildContactList()));
      }
    }
    

     

    (e). main.dart

    This is the launcher class containing main() method. Execution will start with the execution of that method.

    Here is the code:

    import 'package:flutter/material.dart';
    import 'package:using_listview/contact_page.dart';
    
    void main() {
      runApp(new MaterialApp(
        debugShowCheckedModeBanner: false,
        home: new Scaffold(
          appBar: new AppBar(
            title: new Text("Using Listview"),
          ),
          body: new ContactPage(),
        ),
      ));
    }
    

     

    Run

    To run the project simply copy the files. There is no special packages used.

    Here is what you will get:

    Flutter ListView with Letter Icons

    Flutter ListView with Letter Icons

  2. Your work has been of tremendous help towards improving my programming.
    This is the second time i have benefited from your tutorial…Thanks a lot




Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )