Android实现列表元素动态效果

目录
  • 前言
  • AnimatedList 介绍
  • 元素的插入和删除
  • 使用 GlobalKey 获取 AnimatedListState
  • 总结

前言

列表是移动应用中用得最多的组件了,我们也会经常对列表元素进行增加或删除操作,最简单的方法是列表数据变动后,直接 setState 更新列表界面。这种方式存在一个缺陷就是列表元素会突然消失(删除)或出现(添加),当列表元素内容接近时,我们都没法知道操作是否成功了。而如果能够有动效展示这个消失和出现的过程,那么体验就会好很多,比如下面的这种效果,删除元素的时候,会有个逐渐消失的动画,而添加元素的时候会有渐现效果。

Android实现列表元素动态效果

AnimatedList.gif

这里使用到的就是 AnimatedList,本篇文章的示例代码主要来自官方文档:AnimatedList 组件。需要注意的是,毕竟列表带了动画效果,对性能肯定会有影响,建议只对需要对元素进行删除、增加操作的小数据量的列表使用。

AnimatedList 介绍

AnimatedList 是 ListView 的替代,构造函数基本上和 ListView 一致。

constAnimatedList({
Key?key,
requiredthis.itemBuilder,
this.initialItemCount=0,
this.scrollDirection=A编程客栈xis.vertical,
this.reverse=false,
this.controller,
this.primary,
this.physics,
this.shrinkWrap=false,
this.padding,
this.clipBehavior=Clip.hardEdge,
})

不同的地方在于 itemBuilder 的定义不同,itemBuilder 与 ListView 相比,多了一个 animation 参数:

typedefAnimatedListItemBuildewww.cppcns.comr=WidgetFunction(
BuildContextcontext,
intindex,
Animation<double>animation
);

animation是一个 Animation<double>对象,因此可以使用 animation 来构建元素的过渡动画。比如我们这里的示例就使用了 FadeTransition 来构建列表元素,从而有渐现效果。

classListItemextendsStatelessWidget{
constListItem({
Key?key,
requiredthis.onRemove,
requiredthis.animation,
requiredthis.item,
}):super(key:key);

finalAnimation<double>animation;
finalValueChangedonRemove;
finalintitem;HkKhvWnv

@override
Widgetbuild(BuildContextcontext){
returnPadding(
padding:constEdgeInsets.all(2.0),
child:FadeTransition(
opacity:animation,
child:Container(
child:Row(children:[
Expanded(
child:Text(
'Item$item',
style:TextStyle(
color:Colors.blue,
),
),
),
IconButton(
onPressed:(){
onRemove(this.item);
},
icon:Icon(Icons.delete_forever_rounded,color:Colors.grey),
),
]),
),
),
);
}
}

元素的插入和删除

使用 AnimatedList 时,我们需要调用 AnimatedListState 的insertItem 和 removeItem 方法来操作,而不能直接操作完数据后刷新界面。也就是编程客栈在插入和删除数据的时候,应该是先修改列表数据,然后再调用AnimatedListState的 insertItem 或 removeItem 方法来刷新列表界面。例如删除元素的代码:

EremoveAt(in编程客栈tindex){
finalEremovedItem=_items.removeAt(index);

if(removedItem!=null){
_animatedList!.removeItem(
index,
(BuildContextcontext,Animation<double>animation){
returnremovedItemBuilder(removedItem,context,animation);
},
);
}
returnremovedItem;
}

这里 removedItem接收两个参数,一个是要移除元素的下标,另一个是一个构建移除元素的方法 builder。之所以要这个方法是因为元素实际从列表马上移除的,为了在动画过渡时间内还能够看到被移除的元素,需要通过这种方式来构建一个被移除的元素来感觉是动画删除的。这里也可以使用 animation 参数自定义动画效果。insertItem 方法没有 builder 参数,它直接将新插入的元素传给 AnimatedList 的 builder 方法来插入新的元素,这样能够保持和列表新增元素的动效一致。

Android实现列表元素动态效果

扫一扫手机访问