Open In App

Flutter – Animate Items in List Using AnimatedList

Last Updated : 30 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The AnimatedList widget in Flutter is used to create a list that automatically animates changes to its items. It’s particularly useful when you want to add or remove items from a list with smooth animations. In this article, we are going to see how the list is animated when an item is deleted or added to the list. In this article, we are going to implement the AnimatedList widget. A sample video is given below to get an idea about what we are going to do in this article.

Basic Syntax of AnimatedList Widget

AnimatedList(
key: GlobalKey<AnimatedListState>(), // A unique key to identify the list
initialItemCount: itemCount, // The initial number of items in the list
itemBuilder: (BuildContext context, int index, Animation<double> animation) {
// The builder function for creating list items
return YourListItemWidget(item: yourDataList[index], animation: animation);
},
)

Required Tools

To build this app, you need the following items installed on your machine:

  • Visual Studio Code / Android Studio
  • Android Emulator / iOS Simulator / Physical Device device.
  • Flutter Installed
  • Flutter plugin for VS Code / Android Studio.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




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


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch:
            Colors.green, // Set the app's primary theme color to green
      ),
      debugShowCheckedModeBanner: false,
      home: MyAnimatedList(),
    );
  }
}


Step 5: Create MyAnimatedList Class

In this class we are going to Implement the AnimatedList widget that help to Animated the list when an item is added or removed. This class contains 3 methods :

  • _addItem method is used to add a new item to the list.
  • _removeItem method is used to remove an item from the list.
  • buildItem is a helper method that builds each item in the list. It uses SizeTransition for the animation effect.

Comments are added for better understanding.

AnimatedList(
key: _listKey,
initialItemCount: _items.length,
itemBuilder: (context, index, animation) {
return buildItem(_items[index], animation); // Build each list item
},
),

Dart




class MyAnimatedList extends StatefulWidget {
  @override
  _MyAnimatedListState createState() => _MyAnimatedListState();
}
  
class _MyAnimatedListState extends State<MyAnimatedList> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  List<String> _items = [
    'Item 1',
    'Item 2',
    'Item 3',
    'Item 4',
    'Item 5',
    'Item 6',
    'Item 7',
    'Item 8',
    'Item 9',
    'Item 10'
  ];
  
  void _addItem() {
    final newIndex = _items.length; // Calculate the index for the new item
    final newItem = 'Item ${newIndex + 1}'; // Create a new item
  
    // Update the underlying data list
    setState(() {
      _items.add(newItem);
    });
  
    // Insert the new item into the AnimatedList
    _listKey.currentState!.insertItem(newIndex);
  }
  
  void _removeItem(int index) {
    final removedItem = _items[index];
  
    // Remove the item from the data list
    setState(() {
      _items.removeAt(index);
    });
  
    // Remove the item from the AnimatedList with animation
    _listKey.currentState!.removeItem(
      index,
      (context, animation) => buildItem(removedItem, animation),
    );
  }
  
  Widget buildItem(String item, Animation<double> animation) {
    return SizeTransition(
      sizeFactor: animation,
      child: ListTile(
        title: Text(item), // Display the item's text
        trailing: IconButton(
          icon: Icon(Icons.delete), // Display a delete icon
          onPressed: () =>
              _removeItem(_items.indexOf(item)), // Remove the item when pressed
        ),
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AnimatedList Example'), // Set the app bar title
      ),
      body: AnimatedList(
        key: _listKey,
        initialItemCount: _items.length,
        itemBuilder: (context, index, animation) {
          return buildItem(_items[index], animation); // Build each list item
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addItem, // Add a new item when the FAB is pressed
        child: Icon(Icons.add), // Display a plus icon
      ),
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch:
            // Set the app's primary 
            // theme color to green
            Colors.green, 
      ),
      debugShowCheckedModeBanner: false,
      home: MyAnimatedList(),
    );
  }
}
  
class MyAnimatedList extends StatefulWidget {
  @override
  _MyAnimatedListState createState() => _MyAnimatedListState();
}
  
class _MyAnimatedListState extends State<MyAnimatedList> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  List<String> _items = [
    'Item 1',
    'Item 2',
    'Item 3',
    'Item 4',
    'Item 5',
    'Item 6',
    'Item 7',
    'Item 8',
    'Item 9',
    'Item 10'
  ];
  
  void _addItem() {
    final newIndex = _items.length; // Calculate the index for the new item
    final newItem = 'Item ${newIndex + 1}'; // Create a new item
  
    // Update the underlying data list
    setState(() {
      _items.add(newItem);
    });
  
    // Insert the new item into the AnimatedList
    _listKey.currentState!.insertItem(newIndex);
  }
  
  void _removeItem(int index) {
    final removedItem = _items[index];
  
    // Remove the item from the data list
    setState(() {
      _items.removeAt(index);
    });
  
    // Remove the item from the AnimatedList with animation
    _listKey.currentState!.removeItem(
      index,
      (context, animation) => buildItem(removedItem, animation),
    );
  }
  
  Widget buildItem(String item, Animation<double> animation) {
    return SizeTransition(
      sizeFactor: animation,
      child: ListTile(
        title: Text(item), // Display the item's text
        trailing: IconButton(
          icon: Icon(Icons.delete), // Display a delete icon
          onPressed: () =>
              _removeItem(_items.indexOf(item)), // Remove the item when pressed
        ),
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AnimatedList Example'), // Set the app bar title
      ),
      body: AnimatedList(
        key: _listKey,
        initialItemCount: _items.length,
        itemBuilder: (context, index, animation) {
          return buildItem(_items[index], animation); // Build each list item
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addItem, // Add a new item when the FAB is pressed
        child: Icon(Icons.add), // Display a plus icon
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads