Flutter ListView example with ListView.builder

In this tutorial, we’re gonna build a Flutter App that shows a ListView. We are using ListView.builder constructor that creates items when they are scrolled onto the screen. The ListView also supports removing item from the list.

More Practice:
Flutter SQLite example – CRUD Operations with ListView & sqflite plugin
Flutter Firestore example – Firebase Firestore CRUD with ListView
Flutter Firebase Database example – Firebase Database CRUD with ListView

Flutter Dismissible example – Swipe to dismiss/remove Item in ListView

Overview

Flutter App

We will build a Flutter App that can display a List of Post objects, we can also click on the circle Remove Button to delete a Post from the List. This will update the UI immediately because we use StatefulWidget.

flutter-listview-example

List of items with ListView

Initialize the List

We will implement initState() method and call setState() to initialize the List.


class ListViewApp extends StatefulWidget {
  @override
  _ListViewState createState() => new _ListViewState();
}

class _ListViewState extends State {
  final List items = new List();

  @override
  void initState() {
    super.initState();
    setState(() {
      items.add(new Post(...));
      items.add(new Post(...));
      // ...
    });
  }
Use ListView.builder

To display items on the List, we need to render each Object as a Widget.
So we use ListView.builder with itemBuilder callback that returns built-in ListTile Widget for visual structure.


class _ListViewState extends State {

  // ...
  @override
  Widget build(BuildContext context) {
    return MaterialApp(...
      ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, position) {
          return ListTile(
            title: Text('${items[position].title}'),
            subtitle: Text('${items[position].body}'),
            leading: ...
            onTap: () => _onTapItem(context, items[position]),
          );
        },
      );
    );
  }

  void _onTapItem(BuildContext context, Post post) {
    Scaffold
        .of(context)
        .showSnackBar(new SnackBar(content: new Text(post.id.toString() + ' - ' + post.title)));
  }
}

We also play with onTap callback to do something when user tap on any item.

Practice

Create a DataModel Class

lib/post.dart


class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post(this.userId, this.id, this.title, this.body);
}

Create & run a Custom StatefulWidget

main/post.dart


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

void main() {
  runApp(ListViewApp());
}

class ListViewApp extends StatefulWidget {
  @override
  _ListViewState createState() => new _ListViewState();
}

class _ListViewState extends State {
  final List items = new List();

  @override
  void initState() {
    super.initState();
    setState(() {
      items.add(new Post(
        1,
        2,
        'qui est esse',
        'est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla',
      ));
      items.add(new Post(
        1,
        3,
        'ea molestias quasi exercitationem repellat qui ipsa sit aut',
        'et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut',
      ));
      items.add(new Post(
        2,
        4,
        'eum et est occaecati',
        'ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit',
      ));
      items.add(new Post(
        2,
        5,
        'nesciunt quas odio',
        'repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque',
      ));
      items.add(new Post(
        3,
        6,
        'dolorem eum magni eos aperiam quia',
        'ut aspernatur corporis harum nihil quis provident sequi\nmollitia nobis aliquid molestiae\nperspiciatis et ea nemo ab reprehenderit accusantium quas\nvoluptate dolores velit et doloremque molestiae',
      ));
      items.add(new Post(
        3,
        7,
        'magnam facilis autem',
        'dolore placeat quibusdam ea quo vitae\nmagni quis enim qui quis quo nemo aut saepe\nquidem repellat excepturi ut quia\nsunt ut sequi eos ea sed quas',
      ));
      items.add(new Post(
        3,
        8,
        'dolorem dolore est ipsam',
        'dignissimos aperiam dolorem qui eum\nfacilis quibusdam animi sint suscipit qui sint possimus cum\nquaerat magni maiores excepturi\nipsam ut commodi dolor voluptatum modi aut vitae',
      ));
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'JSA ListView Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('ListView Demo'),
          centerTitle: true,
          backgroundColor: Colors.blue,
        ),
        body: Center(
          child: ListView.builder(
              itemCount: items.length,
              padding: const EdgeInsets.all(15.0),
              itemBuilder: (context, position) {
                return Column(
                  children: [
                    Divider(height: 5.0),
                    ListTile(
                      title: Text(
                        '${items[position].title}',
                        style: TextStyle(
                          fontSize: 22.0,
                          color: Colors.deepOrangeAccent,
                        ),
                      ),
                      subtitle: Text(
                        '${items[position].body}',
                        style: new TextStyle(
                          fontSize: 18.0,
                          fontStyle: FontStyle.italic,
                        ),
                      ),
                      leading: Column(
                        children: [
                          CircleAvatar(
                            backgroundColor: Colors.blueAccent,
                            radius: 35.0,
                            child: Text(
                              'User ${items[position].userId}',
                              style: TextStyle(
                                fontSize: 22.0,
                                color: Colors.white,
                              ),
                            ),
                          ),
                          IconButton(
                            icon: const Icon(Icons.remove_circle_outline),
                            onPressed: () {
                              setState(() {
                                items.removeAt(position);
                              });
                            },
                          ),
                        ],
                      ),
                      onTap: () => _onTapItem(context, items[position]),
                    ),
                  ],
                );
              }),
        ),
      ),
    );
  }

  void _onTapItem(BuildContext context, Post post) {
    Scaffold
        .of(context)
        .showSnackBar(new SnackBar(content: new Text(post.id.toString() + ' - ' + post.title)));
  }
}

Source Code

listview_example



By grokonez | July 8, 2018.

Last updated on May 6, 2021.



Related Posts


2 thoughts on “Flutter ListView example with ListView.builder”

Got Something To Say:

Your email address will not be published. Required fields are marked *

*