Flutter – Add Item to ListView Dynamically

Add Item to ListView Dynamically in Flutter

In this tutorial, we will learn how to add an item to a ListView dynamically using Expanded widget and ListView widget.

This tutorial is an extension of how to build a ListView from List of Items.

To build a ListView that can accept items to be added dynamically, wrap ListView in Extended widget.

Sample Code Snippet

Following is a quick code snippet, where items list is transformed to ListView.

List<E> items = <E>[...];

Expanded(
  child: ListView.builder (
    itemCount: items.length,
    itemBuilder: (BuildContext context, int index) {
      return <Widget>;
    }
  )
)

Whenever items list is updated, ListView shall be updated automatically.

Also, note that Expanded widget should be placed inside a Flex widget. So, in the following example, we shall place Expanded widget in Column widget.

Example

This example Flutter Application demonstrates how to create a ListView that can dynamically update itself when the associated list changes.

To recreate this example, create a basic Flutter Application and replace main.dart with the following code.

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyApp> {
  final List<String> names = <String>['Aby', 'Aish', 'Ayan', 'Ben', 'Bob', 'Charlie', 'Cook', 'Carline'];
  final List<int> msgCount = <int>[2, 0, 10, 6, 52, 4, 0, 2];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Tutorial - googleflutter.com'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: names.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  height: 50,
                  margin: EdgeInsets.all(2),
                  color: msgCount[index]>=10? Colors.blue[400]:
                    msgCount[index]>3? Colors.blue[100]: Colors.grey,
                  child: Center(
                    child: Text('${names[index]} (${msgCount[index]})',
                      style: TextStyle(fontSize: 18),
                    )
                  ),
                );
              }
            )
          )
        ]
      )
    );
  }
}

When you run this application, you will get UI as shown in the below screenshot.

Let us add a TextField to add a list item to the list dynamically.

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyApp> {
  final List<String> names = <String>['Aby', 'Aish', 'Ayan', 'Ben', 'Bob', 'Charlie', 'Cook', 'Carline'];
  final List<int> msgCount = <int>[2, 0, 10, 6, 52, 4, 0, 2];

  TextEditingController nameController = TextEditingController();

  void addItemToList(){
    setState(() {
      names.insert(0,nameController.text);
      msgCount.insert(0, 0);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Tutorial - googleflutter.com'),
      ),
      body: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(20),
            child: TextField(
              controller: nameController,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Contact Name',
              ),
            ),
          ),
          RaisedButton(
            child: Text('Add'),
            onPressed: () {
              addItemToList();
            },
          ),
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: names.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  height: 50,
                  margin: EdgeInsets.all(2),
                  color: msgCount[index]>=10? Colors.blue[400]:
                    msgCount[index]>3? Colors.blue[100]: Colors.grey,
                  child: Center(
                    child: Text('${names[index]} (${msgCount[index]})',
                      style: TextStyle(fontSize: 18),
                    )
                  ),
                );
              }
            )
          )
        ]
      )
    );
  }
}

Run this application, and you should see a TextField widget and a Add button to add an item to the list dynamically. Type in some name and click on Add button. The item will be added at the top of the list dynamically.

Summary

In this Flutter Tutorial, we learned how to add an item to ListView dynamically using Expanded and ListView.builder().

Desclaimer: We are not affiliated, associated, authorized, endorsed by, or in any way officially connected with the Google, Apple or Flutter, or any of its subsidiaries or its affiliates. The names Google, Apple and Flutter as well as related names, marks, emblems and images are registered trademarks of their respective owners. This site googleflutter.com covers tutorials related to Flutter developed by Google.