使用AnimatedList的Flutter Dismissable撤消动画

时间:2018-11-06 16:04:45

标签: dart flutter

代码:

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

为简单起见,我使用Timer在1500毫秒后添加删除的号码。一切正常,但是更新列表(在1500毫秒后)后我看不到动画,如何使用animation参数为列表制作动画?

截屏: enter image description here


TL; DR:将项目放回AnimatedList时如何制作动画?

2 个答案:

答案 0 :(得分:0)

要使用AnimatedList插入项目,您需要调用方法AnimatedListState.insertItem(int index)

AnimatedList.of(context).insertItem(0);

您还可以使用AnimatedListState

获得GlobalKey
final foo = GlobalKey<AnimatedListState>();


@override
Widget build(BuildContext context) {
  return AnimatedList(
    key: foo,
    // ...
  );
}

  // elsewhere
foo.currentState.insertItem(0);

答案 1 :(得分:0)

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