Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Dismissible undo animation using AnimatedList

Tags:

flutter

dart

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?

Screenshot: enter image description here


TL;DR: How can I have animation when the item is put back in the AnimatedList?


1 Answers

enter image description here

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());
          });
        },
      );
    },
  );
}