Reputation:
Code:
Widget build(BuildContext context) {
++flag;
return AnimatedList(
key: Key(flag.toString()),
initialItemCount: numbers.length,
itemBuilder: (context, index, animation) {
return Dismissible(
key: Key(numbers[index].toString()),
background: Container(color: Colors.green),
child: ListTile(title: Text("Item = ${numbers[index].toString()}")),
onDismissed: (direction) {
setState(() => numbers.removeAt(index));
Timer(Duration(milliseconds: 1500), () => setState(() => numbers.insert(index, index)));
},
);
},
);
}
For simplicity I am using Timer
to add the deleted number after 1500 ms. Everything works great but I can't see the animation when the list is updated (after 1500 ms), how can I make use of animation
parameter to animate the list?
TL;DR: How can I have animation when the item is put back in the AnimatedList
?
Upvotes: 4
Views: 2748
Reputation:
List<int> _list = List.generate(5, (i) => i);
GlobalKey<AnimatedListState> _key = GlobalKey();
int _index;
Widget build(BuildContext context) {
return Scaffold(
body: _myWidget(),
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.undo),
onPressed: () {
_list.insert(_index, _index);
_key.currentState.insertItem(_index);
},
),
],
),
);
}
Widget _myWidget() {
return AnimatedList(
key: _key,
initialItemCount: _list.length,
itemBuilder: (context, index, animation) {
return Dismissible(
key: Key("${_list[index]}"),
child: SizeTransition(
sizeFactor: animation,
child: ListTile(title: Text("Item = ${_list[index]}")),
),
background: Container(color: Colors.green),
onDismissed: (direction) {
setState(() {
_index = index;
_list.removeAt(index);
_key.currentState.removeItem(index, (_, __) => Container());
});
},
);
},
);
}
Upvotes: 4
Reputation: 277037
To insert items using AnimatedList
, you need to call the method AnimatedListState.insertItem(int index)
AnimatedList.of(context).insertItem(0);
You can also obtain the AnimatedListState
using a GlobalKey
final foo = GlobalKey<AnimatedListState>();
@override
Widget build(BuildContext context) {
return AnimatedList(
key: foo,
// ...
);
}
// elsewhere
foo.currentState.insertItem(0);
Upvotes: 0