1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| class _AnimatedListRouteTestState extends State<AnimatedListTestRoute> { var data = <String>[]; int counter = 5;
final globalKey = GlobalKey<AnimatedListState>();
@override void initState() { for (var i = 0; i < counter; i++) { data.add('${i + 1}'); } super.initState(); }
@override Widget build(BuildContext context) { return Stack( children: [ AnimatedList( key: globalKey, initialItemCount: data.length, itemBuilder: ( BuildContext context, int index, Animation<double> animation, ) { return FadeTransition( opacity: animation, child: buildItem(context, index), ); }, ), buildAddBtn(), ], ); }
Widget buildAddBtn() { return Positioned( bottom: 30, left: 0, right: 0, child: FloatingActionButton( child: Icon(Icons.add), onPressed: () { data.add('${++counter}'); globalKey.currentState!.insertItem(data.length - 1); print('添加 $counter'); }, ), ); }
Widget buildItem(context, index) { String char = data[index]; return ListTile( key: ValueKey(char), title: Text(char), trailing: IconButton( icon: Icon(Icons.delete), onPressed: () => onDelete(context, index), ), ); }
void onDelete(context, index) { setState(() { globalKey.currentState!.removeItem( index, (context, animation) { var item = buildItem(context, index); print('删除 ${data[index]}'); data.removeAt(index); return FadeTransition( opacity: CurvedAnimation( parent: animation, curve: const Interval(0.5, 1.0), ), child: SizeTransition( sizeFactor: animation, axisAlignment: 0.0, child: item, ), ); }, duration: Duration(milliseconds: 200), ); }); } }
|
v1.5.2