Flutter ListView using Animated List with Example
Flutter ListView using Animated List with Example

Hi Guys, Welcome to Proto Coders Point , In this Flutter Tutorial we will Implement how to display Listview using Flutter Animated List widget with a simple example.

What is Animated List widget in flutter ?

Suppose you have an application that simply show a ListView and some times items may get updated ( inserted or removed from the list but with normal listView application user will not get to know about the update.

For this reason it would be better if we can show some kind of Animation effect while any item is added or removed from the listview, so the user will be aware of the update. In Flutter Development, we can do it easily using AnimatedList Class

In this Flutter Tutorial example, We gonna store the data in :

List<String> where all the data will be stored in Array form.

I am making use of english_words package to randomly generate a work and add it in our list<String>.

Remember you need to add english_words in pubspec.yaml . get Library here

We also need an instance of GlobalKey<AnimatedListState> so that we can store the state of the AnimatedList widget.

Let’s begin implementing AnimatedList in our flutter project.

Demo on how final code looks like

Flutter animated List view GIF video
Flutter animated List view GIF video

Introduction to basic layout of this project

In this example the layout design is very simple, it contain are Three RaisedButton at the bottom of the app, this button consist of child widget as Icon and Texts. It has functionally such as adding new item or removing the last time or removing all the item from ListView at once.

class AnimatedListExampleState extends State<AnimatedListExample> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey();

  List<String> _data = [
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
  ];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Animated List Example'),
        backgroundColor: Colors.blueAccent,
      ),
      persistentFooterButtons: <Widget>[
        RaisedButton(
          child: Icon(Icons.add),
          color: Colors.green,
          onPressed: () {
            _addAnItem();
          },
        ),
        RaisedButton(
          child: Icon(Icons.remove),
          color: Colors.red[200],
          onPressed: () {
            _removeLastItem();
          },
        ),
        RaisedButton(
          child: Text(
            'Remove all',
            style: TextStyle(fontSize: 20, color: Colors.white),
          ),
          color: Colors.red,
          onPressed: () {
            _removeAllItems();
          },
        ),
      ],
      body: Container();
  }

Build Animation for Animated ListView

To show an animation effect, we’re going call a function that simple returns a widget, that widget is wraped into any Transaction Such as:

  • SlideTransition
  • ScaleTransition
  • SizeTransition
  • RotationTransition
  • PositionedTransition
  • RelativePositionedTransition
  • DecoratedBoxTransition
  • AlignTransition
  • DefaultTextStyleTransition
  • FadeTransition

For This example, if we use ScaleTransition,

Widget _buildItem(
    BuildContext context, String item, Animation<double> animation) {
  TextStyle textStyle = new TextStyle(fontSize: 20, color: Colors.white);

  return Padding(
    padding: const EdgeInsets.all(2.0),
    child: ScaleTransition(
      child: SizedBox(
        height: 100.0,
        child: Card(
          color: Colors.lightBlueAccent,
          child: Center(
            child: Text(item, style: textStyle),
          ),
        ),
      ),
      scale: animation,
    ),
  );
}

Creating AnimatedList

In the above snippet code of layout , in body property we simply have an empty container(), we need to replace the body with our listview i’e AnimatedList, To be able to build AnimatedList View,

Here we us _listKey as key parameter and number of items as initialItemCount

body: AnimatedList(
        key: _listKey,
        initialItemCount: _data.length,
        itemBuilder: (context, index, animation) =>
            _buildItem(context, _data[index], animation),
      ),

Insert Item in Animated ListView

To be able to insert an item in AnimatedList, we need to first insert it to _data string array, After that,  we can insert the aminated list using insertItem. Each Time an item is been added the itemBuilder will be called.

void _addAnItem() {
   _data.insert(0, WordPair.random().toString()); //
   _listKey.currentState.insertItem(0);  //
 }

Remove Item

Here are have 2 ways to remove an item:

  1.  Remove latest item
  2.  Remove all item

1. Remove latest item from AnimatedList

To remove the latest item, we need to use removeItem method. That remove item from the _data list

void _removeLastItem() {
    String itemToRemove = _data[0];

    _listKey.currentState.removeItem(
      0,
      (BuildContext context, Animation<double> animation) =>
          _buildItem(context, itemToRemove, animation),
      duration: const Duration(milliseconds: 250),
    );

    _data.removeAt(0);
  }

In the above Snippet code, we are keeping note of latest item “itemToRemove”, After that, we are removing that item from _listKey and then finally remove that item from _data List using removeAt() method.

2. Remove All the item from AnimatedList

Likewise to remove all the item from listview, Firstly we are counting total number of item present in _data using length function, then with the help of for loop we are traversing upto last item in _data list and remove all the item from _data List and then just update the AnimatedList.

void _removeAllItems() {
    final int itemCount = _data.length;

    for (var i = 0; i < itemCount; i++) {
      String itemToRemove = _data[0];
      _listKey.currentState.removeItem(
        0,
        (BuildContext context, Animation<double> animation) =>
            _buildItem(context, itemToRemove, animation),
        duration: const Duration(milliseconds: 250),
      );

      _data.removeAt(0);
    }
  }

 

Complete Code of Flutter AnimatedList View

copy paste the below line of dart code in main.dart

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ListView Example',
      home: AnimatedListExample(),
    );
  }
}

class AnimatedListExample extends StatefulWidget {
  @override
  AnimatedListExampleState createState() {
    return new AnimatedListExampleState();
  }
}

class AnimatedListExampleState extends State<AnimatedListExample> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey();

  List<String> _data = [
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
  ];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Animated List Example'),
        backgroundColor: Colors.blueAccent,
      ),
      persistentFooterButtons: <Widget>[
        RaisedButton(
          child: Icon(Icons.add),
          color: Colors.green,
          onPressed: () {
            _addAnItem();
          },
        ),
        RaisedButton(
          child: Icon(Icons.remove),
          color: Colors.red[200],
          onPressed: () {
            _removeLastItem();
          },
        ),
        RaisedButton(
          child: Text(
            'Remove all',
            style: TextStyle(fontSize: 20, color: Colors.white),
          ),
          color: Colors.red,
          onPressed: () {
            _removeAllItems();
          },
        ),
      ],
      body: AnimatedList(
        key: _listKey,
        initialItemCount: _data.length,
        itemBuilder: (context, index, animation) =>
            _buildItem(context, _data[index], animation),
      ),
    );
  }

  Widget _buildItem(
      BuildContext context, String item, Animation<double> animation) {
    TextStyle textStyle = new TextStyle(fontSize: 20, color: Colors.white);

    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: ScaleTransition(
        child: SizedBox(
          height: 100.0,
          child: Card(
            color: Colors.lightBlueAccent,
            child: Center(
              child: Text(item, style: textStyle),
            ),
          ),
        ),
        scale: animation,
      ),
    );
  }

  void _addAnItem() {
    _data.insert(0, WordPair.random().toString());
    _listKey.currentState.insertItem(0);
  }

  void _removeLastItem() {
    String itemToRemove = _data[0];

    _listKey.currentState.removeItem(
      0,
      (BuildContext context, Animation<double> animation) =>
          _buildItem(context, itemToRemove, animation),
      duration: const Duration(milliseconds: 250),
    );

    _data.removeAt(0);
  }

  void _removeAllItems() {
    final int itemCount = _data.length;

    for (var i = 0; i < itemCount; i++) {
      String itemToRemove = _data[0];
      _listKey.currentState.removeItem(
        0,
        (BuildContext context, Animation<double> animation) =>
            _buildItem(context, itemToRemove, animation),
        duration: const Duration(milliseconds: 250),
      );

      _data.removeAt(0);
    }
  }
}

All set the flutter app is ready to use with AnimatedList view Effect

Recommended Articles

listwheelscrollview3D ListView in flutter

Flutter Image Slider