• Docs
  • Showcase
  • Community
  • DMCA
Sunday, February 28, 2021
Flutter Website
No Result
View All Result
  • Login
  • Register
Flutter Website
  • Home
  • Categories
    • Flutter App
    • Flutter Examples
    • Flutter Github
    • Flutter News
    • Flutter PDF
    • Flutter Tips & Trick
    • Flutter Tutorial
    • Flutter UI
    • Flutter Video
    • Flutter VS
    • Flutter Wiki
    • Flutter With
  • Flutter
    • Flutter for Mobile
    • Flutter for Web
      • Widget Sample
    • Flutter for Desktop
    • Tools
      • Codemagic
      • Flutter Studio
      • Supernova
  • Showcase
  • Community
  • Advertisement
  • Hire Us
No Result
View All Result
Flutter Website
Home Flutter Tips & Trick

How To Animate Items In List Using AnimatedList In Flutter

Guide to show animation when items are entered and exit in a list using AnimatedList widget in Flutter.

flutter by flutter
Reading Time: 18min read
520
How to animate items in list using animatedlist in flutter
464
SHARES
663
VIEWS
Share on FacebookShare on TwitterShare on LinkedinShare to Whatsapp

Table of Contents

    • The problem
    • The solution
    • So how do we do that in Flutter?
  • ? Presenting the AnimatedList Widget
    • Let’s try to build something like this.
    • Animated Widget Code looks like this
    • Properties:
  • Let’s make it work step by step
  • How do we add curves to animation?
    • ? Bonus
  • Different types of animation
    • Resize the item ↕
    • Rotate the item ⟳
    • Slide, Resize, and Rotate the item together. →↕⟳
  • How to animate the items rendered initially.

The problem

List view in general is very essential in any front end framework. It contains the list of data called items to be displayed to the user. There is a high chance that item in a list may be added, removed, and changed. Now the problem is whenever any item added or removed in between the list while the user is interacting with it, This sudden change sometimes can create confusion to the user.

How to animate items in list using animatedlist in flutter

The solution

The simple solution is to provide a visual experience of items being added or removed by animating it. ?

So how do we do that in Flutter?

? Presenting the AnimatedList Widget

An AnimatedList is a List that animates the item when inserted or removed.

Let’s try to build something like this.

How to animate items in list using animatedlist in flutter

Animated Widget Code looks like this

AnimatedList(
  itemBuilder: (context, index, animation) {
    return slideIt(context, index, animation);
  },
)

Properties:

◉ itemBuilder: This is the required parameter and is used to build items in a list. You can simply return a widget of your choice to build any item and they will be only built when they are scrolled into the view. Since we are dealing with animation, we get an animation object that will be used by the item to animate.

◉ controller: This is used to control the scroll position of the list.

◉ key: This is required in case we need to access the AnimatedList from outside and not from within the item itself.

◉ initialItemCount: It is used to load initial items when the list is loaded. These initial items won’t be animated. It defaults to 0.

◉ scrollDirection: It decides the scrolling behaviors of items.

// Items can be scrolled only bottom to top and vica versa.
scrollDirection: Axis.vertical,// Items can be scrolled only left to right and vica versa.
scrollDirection: Axis.horizontal,

◉ reverse: This is used to decide whether the list will be scrolled in the reading direction. It defaults to false. In the App by default, the reading direction is left-to-right so the list will be scrolled left to right. If we set this flag to true, the list will scroll in a right-to-left direction (opposite).

◉ primary: In iOS when we click on the status bar the list will scroll to top. It defaults to true when the scroll direction is vertical and the controller is null.

◉ physics: It decides how the scroll should behave on user input.

◉ shrinkWrap: It is used to decide whether the size (extent) of the list should take full available space or match it to the size of items in the list.

◉ padding: This simply adds padding around the items on the list.


Let’s make it work step by step

Step ➊: Prepare variables

/// Will used to access the Animated list 
final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>();/// This holds the items
List<int> _items = [];/// This holds the item count
int counter = 0;

Step ➋: Deploy the AnimatedList.

AnimatedList(
  key: listKey,
  initialItemCount: _items.length,
  itemBuilder: (context, index, animation) {
    return slideIt(context, index, animation); // Refer step 3
  },
)

Step ➌: Write a widget to display as Items in a list.

Widget slideIt(BuildContext context, int index, animation) {
  int item = _items[index];
  TextStyle textStyle = Theme.of(context).textTheme.headline4;
  return SlideTransition(
    position: Tween<Offset>(
      begin: const Offset(-1, 0),
      end: Offset(0, 0),
    ).animate(animation),
    child: SizedBox( // Actual widget to display
      height: 128.0,
      child: Card(
        color: Colors.primaries[item % Colors.primaries.length],
        child: Center(
          child: Text('Item $item', style: textStyle),
        ),
      ),
    ),
  );
}

Note: ✍

The main item widget i.e SizedBox is wrapped inside SlideTransition. SlideTransition needs the object of Animation<Offset> and we are getting the object of Animation<double> so we use .animate method to convert it.

Step ➍: Insert the Item.

listKey.currentState.insertItem(0,
    duration: const Duration(milliseconds: 500));
_items = []
  ..add(counter++)
  ..addAll(_items);

For this example, we are adding any new item to the first index.

Step ➎: Remove the Item.

listKey.currentState.removeItem(
    0, (_, animation) => slideIt(context, 0, animation),
    duration: const Duration(milliseconds: 500));
_items.removeAt(0);

Also removing it from the first index only.

Note: ✍

  1. Whenever we insert the item in the animated list we should also update the actual list.
  2. While removing the item in step 5 we also have to pass the same widget which is used to create items because when AnimatedList removes the item, Its index is no longer available but still, it needs the UI of that item to animate like this (_, animation) => slideIt(context, 0, animation).

Here is the full code ?

How do we add curves to animation?

CurvedAnimation is here to the rescue.

CurvedAnimation is useful when you want to apply a non-linear Curve to an animation object, especially if you want different curves when the animation is going forward vs when it is going backward.

SlideTransition(
  position: Tween<Offset>(
    begin: const Offset(-1, 0),
    end: Offset(0, 0),
  ).animate(CurvedAnimation(
      parent: animation,
      curve: Curves.bounceIn,
      reverseCurve: Curves.bounceOut)),
  child: SizedBox(
    height: 128.0,
    child: Card(
      color: Colors.primaries[item % Colors.primaries.length],
      child: Center(
        child: Text('Item $item', style: textStyle),
      ),
    ),
  ),
);

Instead of just passing animation, we pass CurvedAnimation with the required curve. And the result looks like this.

How to animate items in list using animatedlist in flutter

You see items bouncing on entry and exit. Right?

? Bonus

You can check all the curves here

Different types of animation

So far we have seen the item is just entering from left to right and taking exit in the reverse direction. This is because we have used the SlideTransition widget.

You can create any animation for the item that you can think of. The widget you choose will just have to accept the object of Animation<double>

Resize the item ↕

How to animate items in list using animatedlist in flutter

Widget sizeIt(BuildContext context, int index, animation) {
  int item = _items[index];
  TextStyle textStyle = Theme.of(context).textTheme.headline4;
  return SizeTransition(
    axis: Axis.vertical,
    sizeFactor: animation,
    child: SizedBox(
      height: 128.0,
      child: Card(
        color: Colors.primaries[item % Colors.primaries.length],
        child: Center(
          child: Text('Item $item', style: textStyle),
        ),
      ),
    ),
  );
}

The sizeFactor property accepts the Animation<double> which we can easily pass what we have got from the itemBuilder.

Rotate the item ⟳

How to animate items in list using animatedlist in flutter

Widget rotateIt(BuildContext context, int index, animation) {
  int item = _items[index];
  TextStyle textStyle = Theme.of(context).textTheme.headline4;
  return RotationTransition(
    turns: animation,
    child: SizedBox(
      height: 128.0,
      child: Card(
        color: Colors.primaries[item % Colors.primaries.length],
        child: Center(
          child: Text('Item $item', style: textStyle),
        ),
      ),
    ),
  );
}

Slide, Resize, and Rotate the item together. →↕⟳

How to animate items in list using animatedlist in flutter

SlideTransition(
  position: Tween<Offset>(
    begin: const Offset(-1, 0),
    end: Offset(0, 0),
  ).animate(animation),
  child: RotationTransition(
    turns: animation,
    child: SizeTransition(
      axis: Axis.vertical,
      sizeFactor: animation,
      child: SizedBox(
        height: 128.0,
        child: Card(
          color: Colors.primaries[item % Colors.primaries.length],
          child: Center(
            child: Text('Item $item', style: textStyle),
          ),
        ),
      ),
    ),
  ),
);

How to animate the items rendered initially.

Right now AnimatedList is able to animate items that are added or removed after the initial list is displayed. To animate the initial items that are already present in the list, You can manually add items in a list after a delay.

How to animate items in list using animatedlist in flutter

Future<void> _loadItems() async {
  for (int item in _fetchedItems) {
    // 1) Wait for one second
    await Future.delayed(Duration(milliseconds: 1000));
    // 2) Adding data to actual variable that holds the item.
    _items.add(item);
    // 3) Telling animated list to start animation
    listKey.currentState.insertItem(_items.length - 1);
  }
}

That’s it. I hope you have learned something new from this article.

Thanks for reading.

Tags: Flutter CommunityFlutter Weekly

Related Posts

Visualeyes marketing site
Flutter UI

VisualEyes marketing site – UI ideas for flutter

517
Unsplash ios app
Flutter UI

Unsplash iOS app – UI ideas for flutter

515
Quill marketing site
Flutter UI

Quill marketing site – UI ideas for flutter

517
Microsoft outlook ios app
Flutter UI

Microsoft Outlook iOS app – UI ideas for flutter

517
Simba marketing site
Flutter UI

Simba marketing site – UI ideas for flutter

528
Stoic ios app
Flutter UI

Stoic iOS app – UI ideas for flutter

522
  • Flutter & dart – the complete guide [2020 edition]

    Flutter & Dart – The Complete Guide [2020 Edition]

    2271 shares
    Share 908 Tweet 568
  • The Complete 2020 Flutter Development Bootcamp with Dart

    1989 shares
    Share 796 Tweet 497
  • Flutter & Firebase: Build a Complete App for iOS & Android

    1422 shares
    Share 569 Tweet 356
  • Flutter Bloc & Cubit Tutorial

    1296 shares
    Share 518 Tweet 324
  • 40 Beautiful Flutter UI Themes For Developers

    1112 shares
    Share 445 Tweet 278

Made by Google

Flutter is Google’s portable UI toolkit for building beautiful, natively-compiled applications for mobile, web, and desktop from a single codebase.

Follow us

Recent Post

  • Adaptive Layouts part 2 (The Boring Flutter Development Show, Ep. 46)
  • VisualEyes marketing site – UI ideas for flutter
  • Final vs Const – Programming #Shorts
  • Intro to Git – Learning Git and GitHub – Integration and Alternatives
  • Unsplash iOS app – UI ideas for flutter

Popular Post

Flutter & firebase app tutorial #7 – streams

Flutter & Firebase App Tutorial #7 – Streams

528
Flutter – upload image to firebase and get download url

Flutter – Upload Image to Firebase and get Download URL

556

Review Post

Flutter themeswitcher template in flutter

Flutter ThemeSwitcher Template in Flutter

Congratulations, Nice Work, GLWS $7
Rosen – flutter ecommerce ui

Rosen - Flutter Ecommerce UI

Nice Product I am gonna love it. $18
  • [email protected]
  • Flutter Terms
  • Flutter Packages
  • Dart

Copyright © 2021 Flutter Website - by Flutter Team.

No Result
View All Result
  • Home
  • Categories
    • Flutter App
    • Flutter Examples
    • Flutter Github
    • Flutter News
    • Flutter PDF
    • Flutter Tips & Trick
    • Flutter Tutorial
    • Flutter UI
    • Flutter Video
    • Flutter VS
    • Flutter Wiki
    • Flutter With
  • Flutter
    • Flutter for Mobile
    • Flutter for Web
      • Widget Sample
    • Flutter for Desktop
    • Tools
      • Codemagic
      • Flutter Studio
      • Supernova
  • Showcase
  • Community
  • Advertisement
  • Hire Us
  • Login
  • Sign Up

Copyright © 2021 Flutter Website - by Flutter Team.

Welcome Back!

Sign In with Facebook
Sign In with Google
OR

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Sign Up with Facebook
Sign Up with Google
OR

Fill the forms below to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In
This website uses cookies. By continuing to use this website you are giving consent to cookies being used. Visit our Privacy and Cookie Policy.
Go to mobile version