首页 > 其他分享 >Flutter AnimatedList 实现动态列表

Flutter AnimatedList 实现动态列表

时间:2023-12-21 16:59:13浏览次数:29  
标签:index const AnimatedList list 列表 item GlobalKey key Flutter

import 'dart:async';

import 'package:flutter/material.dart';

final GlobalKey _globalKey = GlobalKey();

class MyAnimatedList extends StatelessWidget {
  const MyAnimatedList({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AnimatedList'),
      ),
      body: AnimatedListBody(
        _globalKey,
      ),
      floatingActionButton: FloatingActionButton(onPressed: () {
        var state = _globalKey.currentState as _AnimatedListBodyState;
        state.insterItem();
      }),
    );
  }
}

class AnimatedListBody extends StatefulWidget {
  const AnimatedListBody(Key? key) : super(key: key);

  @override
  State<AnimatedListBody> createState() => _AnimatedListBodyState();
}

class AnimateItem {
  String title;
  GlobalKey key; //用来获取需要删除的组件
  AnimateItem(this.title) : key = GlobalKey();
}

class _AnimatedListBodyState extends State<AnimatedListBody> {
  // 定义一个 [AnimatedListState]类型的key
  final _animateGlobalKey = GlobalKey<AnimatedListState>();
  List<AnimateItem> list = [];
  int count = 0;
  // 插入数据
  void insterItem() {
    list.add(AnimateItem('第$count条数据'));
    count++;
    _animateGlobalKey.currentState!.insertItem(list.length - 1);
  }

  // 删除数据
  // 删除的状态,避免重复点击报错
  Map<GlobalKey, bool> delStateMap = {};
  void removeItem(int index, GlobalKey key) {
    if (delStateMap[key] != true) {
      delStateMap[key] = true;

      var item = key.currentWidget;
      list.removeAt(index);
      _animateGlobalKey.currentState!.removeItem(
        index,
        (context, animation) {
          return FadeTransition(
            opacity: animation,
            child: item,
          );
        },
      );

      Timer.periodic(const Duration(milliseconds: 1000), (timer) {
        delStateMap.remove(key);
        timer.cancel();
      });
    }
  }

  Widget _itemBuild(
      BuildContext context, int index, Animation<double> animate) {
    final item = list[index];
    return FadeTransition(
      opacity: animate,
      child: ListTile(
        key: item.key,
        title: Text(item.title),
        trailing: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () {
            removeItem(index, item.key);
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedList(
      key: _animateGlobalKey,
      initialItemCount: list.length,
      itemBuilder: _itemBuild,
    );
  }
}


标签:index,const,AnimatedList,list,列表,item,GlobalKey,key,Flutter
From: https://www.cnblogs.com/angelwgh/p/17919409.html

相关文章

  • Flutter 编译是pod intsall github 资源下载失败
    在fluterr编译报错然后显示github.xxxxx访问超时处理办法podinstall主要是读取profile文件platform:ios,'9.0'target'YourAppName'douse_frameworks!#这是安装依赖位置pod'SomeDependency'#添加其他依赖项...end想办法下载到github的文......
  • C++ Qt开发:StringListModel字符串列表映射组件
    Qt是一个跨平台C++图形界面开发库,利用Qt可以快速开发跨平台窗体应用程序,在Qt中我们可以通过拖拽的方式将不同组件放到指定的位置,实现图形化开发极大的方便了开发效率,本章将重点介绍QStringListModel字符串映射组件的常用方法及灵活运用。QStringListModel是Qt中用于处理字符......
  • Lazada商品评论列表API:电商行业的实时反馈宝库
    一、引言在当前的电商行业中,获取实时、准确的用户反馈数据对于电商业务运营至关重要。Lazada是东南亚地区领先的电商平台之一,提供了丰富的API接口,其中包括获取商品评论列表API,以便第三方开发者能够获取Lazada内的商品评论信息。本文将深入探讨Lazada商品评论列表API在电商行业中的......
  • Flutter Key 以及通过Key获取子组件的状态和方法
    import'package:flutter/material.dart';classColorItem{GlobalKeykey;Colorcolor;//设置子组件的key,这里用的GlobalKey,用来后面获取子组件//如果不用获取子组件,也可以用ValuekeyColorItem({requiredthis.color}):key=GlobalKey();}classFlutterKe......
  • python之列表的排序、循环、合并
    排序:sorted()显示临时排序cars=['byd','audi','gelly','qirui','chengcheng']print(sorted(cars))print(cars)结果:['audi','byd','chengcheng','gelly','qirui'][�......
  • 想要深入学习Flutter,这篇文章让你一步到位
    前言Flutter是谷歌的移动UI框架,可以快速在iOS和Android上构建高质量的原生用户界面一份代码可以同时生成iOS和Android两个高性能、高保真的应用程序Flutter目标就是使开发人员能够交付在不同平台上都感觉自然流畅的高性能应用程序,并且兼容滚动行为、排版、图标等方面的......
  • iOS项目中加入flutter
    新建一个iOS项目Test在iOS同级目录下建一个flutter modulefluttercreate--templatemodulemy_flutterpodfile编写如下#Uncommentthenextlinetodefineaglobalplatformforyourproject#platform:ios,'9.0'target'Test'do#Commentthenextl......
  • Flutter 使用PageView 自定义无限轮播
    import'package:flutter/material.dart';int_getRealIndex(intindex,intlength){returnindex>=length?index%length:index;}classInfinitySliderextendsStatefulWidget{finalintinitialPage;finalList<Widget>items;......
  • Flutter video_player播放视频
    1、pubspec.yaml文件引入插件dependencies:...video_player:^2.8.12、页面使用(这里我是宽度百分百,高度自适应了)lateVideoPlayerController_controller;Container(width:MediaQuery.of(context).size.width,child:AspectRatio(aspectRatio:_......
  • 列表页删除最后一页的最后一条数据,定位前一页数据
    1、调用后端接口时,返回最大页码数,这样就可以避免//最后一页就剩一条,删除或者取消关注,默认展示前一页if(tableData?.length==0&&currentPage>1){ constbeforePageNum=result?.maxPage==0?1:result?.maxPage; setCurrentPage(beforePageNum);}2、计......