Animated List in Flutter
To create an animated list in Flutter, you can use the AnimatedList
widget. This widget is a scrollable list that animates items when they are inserted or removed.
Here’s an example of how you can use the AnimatedList
widget to create an animated list:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final GlobalKey<AnimatedListState> _listKey = GlobalKey();
List<String> _items = ['Item 1', 'Item 2', 'Item 3'];
void _addItem() {
setState(() {
_items.insert(_items.length, 'New Item');
_listKey.currentState.insertItem(_items.length - 1);
});
}
void _removeItem() {
setState(() {
_items.removeAt(_items.length - 1);
_listKey.currentState.removeItem(_items.length, (context, animation) {
return FadeTransition(
opacity: animation,
child: SizeTransition(
sizeFactor: animation,
child: ListTile(title: Text(_items[_items.length])),
),
);
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Animated List'),
),
body: AnimatedList(
key: _listKey,
initialItemCount: _items.length,
itemBuilder: (context, index, animation) {
return FadeTransition(
opacity: animation,
child: ListTile(title: Text(_items[index])),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _addItem,
child: Icon(Icons.add),
),
),
);
}
}
This code creates an AnimatedList
widget with a list of items, and adds two buttons to add or remove items from the list. When an item is added or removed, the AnimatedList
animates the insertion or removal of the item using the insertItem
and removeItem
methods.
Finally
You can customize the animation by providing a custom itemBuilder
function, which returns a widget that will be animated when an item is inserted or removed. In this example, we're using the FadeTransition
widget to animate the opacity of the list items, and the SizeTransition
widget to animate the size of the items.