Flutter: AnimatedList 一个滚动容器,可在插入或移除项目时为其设置动画
阅读原文时间:2023年07月08日阅读:2
  • Flutter Widget of the Week

    import 'dart:math';
    import 'package:flutter/material.dart';

    void main() => runApp(MyApp());

    class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
    return MaterialApp(
    home: MyHome(),
    );
    }
    }

    class MyHome extends StatefulWidget {
    @override
    _MyHomeState createState() => _MyHomeState();
    }

    class _MyHomeState extends State {
    Tween myTween = Tween(
    begin: Offset(1, 0),
    end: Offset(0, 0),
    );
    var _data = [];
    final _myListKey = GlobalKey();

    Widget myListItem(String d, animation) {
    return SlideTransition(
    position: animation.drive(myTween),
    child: myItem(d),
    );
    }

    Widget myItem(String d) {
    return ListTile(
    title: Text(
    '${d}',
    style: TextStyle(fontSize: 40),
    ),
    trailing: IconButton(
    onPressed: () {
    var index = _data.indexOf(d);
    _data.remove(d);
    _myListKey.currentState.removeItem(
    index, (context, animation) => myListItem(d, animation));
    },
    icon: Icon(Icons.delete_forever),
    ),
    );
    }

    @override
    Widget build(BuildContext context) {
    return Scaffold(
    appBar: AppBar(
    title: Text('Flutter Demo'),
    ),
    floatingActionButton: FloatingActionButton(
    onPressed: () {
    String newv = Random().nextInt(1000).toString();
    _data.add(newv);
    var index = _data.lastIndexOf(newv);
    _myListKey.currentState.insertItem(index);
    },
    child: Icon(Icons.add),
    ),
    body: AnimatedList(
    key: _myListKey,
    initialItemCount: _data.length,
    itemBuilder: (context, int index, Animation animation) {
    return myListItem(_data[index], animation);
    },
    ),
    );
    }
    }