zoukankan      html  css  js  c++  java
  • Flutter: AnimatedList 一个滚动容器,可在插入或移除项目时为其设置动画

    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<MyHome> {
      Tween<Offset> myTween = Tween<Offset>(
        begin: Offset(1, 0),
        end: Offset(0, 0),
      );
      var _data = <String>[];
      final _myListKey = GlobalKey<AnimatedListState>();
    
      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<double> animation) {
              return myListItem(_data[index], animation);
            },
          ),
        );
      }
    }
    
  • 相关阅读:
    2015上阅读计划
    《梦断代码》读书笔记 第2篇
    四则运算3
    求数组中最大子数组的和(一维)
    四则运算2—单元测试
    四则运算2
    《梦断代码》读书笔记 第1篇
    四组运算2(思路)
    四则运算1
    读书笔记
  • 原文地址:https://www.cnblogs.com/ajanuw/p/10926755.html
Copyright © 2011-2022 走看看