[英]Flutter Slidable stays open after item is removed from list
我在 ListView 中使用 Slidable 以便我可以删除项目。 问题是,如果我从列表中删除一个项目,新项目的可滑动打开。 这显然不是想要的行为。 这是一个屏幕视频,以便更好地理解。
我的列表是一个 AnimatedList:
` child: AnimatedList(
padding: EdgeInsets.zero,
shrinkWrap: true,
key: listKey,
initialItemCount: widget.month.memories.length,
itemBuilder: (context, index, animation) {
return slideIt(
context,
widget.month.memories[index],
index,
animation,
);
},
),`
这是我的 Slidable:
` Widget slideIt(
BuildContext context,
Memory memory,
int index,
animation,
) {
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(-1, 0),
end: Offset(0, 0),
).animate(
CurvedAnimation(
parent: animation,
curve: Curves.easeIn,
reverseCurve: Curves.easeOut,
),
),
child: Slidable(
actionPane: SlidableDrawerActionPane(),
actionExtentRatio: 0.25,
movementDuration: Duration(milliseconds: 400),
child: Column(
children: [
MemoryTile(
memory: memory,
monthName: widget.month.name,
onTapped: () {
_removeMemoryAtIndex(index, memory);
print('tap on ${memory.description}');
},
),
SizedBox(
height: scaleWidth(20),
),
],
),
secondaryActions: [
SlideAction(
closeOnTap: false,
color: AppColors.secondary,
onTap: () => {
_removeMemoryAtIndex(index, memory),
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
CupertinoIcons.trash_fill,
color: AppColors.primary,
size: 30,
),
SizedBox(
height: scaleWidth(5),
),
Text(
'Löschen',
style: AppTextStyles.montserratH6SemiBold,
),
SizedBox(
height: scaleWidth(20),
),
],
),
),
],
),
);
}`
AnimatedList 使它变得更加棘手,所以如果您需要更多信息,请告诉我! 我怎样才能解决这个问题?
您应该为您的 slidable 分配一个键。 当 Flutter 管理其状态时,它使用三棵树来完成它:小部件树、元素树和渲染对象树。 当小部件关闭 flutter 时,尝试通过简单的类型相等性将其余小部件与相应元素同步。 所以,这就是为什么您的应用程序会以这种方式运行。 Flutter 取剩余的第一个小部件加上第一个元素,并比较它们是否具有相同的类型。 如果有,则 Flutter 使用元素的状态来显示相应的渲染对象。 元素树的最后一个元素将被删除。 因此,您需要添加键,Flutter 还会使用它们以理想的方式同步小部件和元素。
每个 Flutter 小部件都有一个Key
字段。 您应该在创建小部件实例时分配它们。 您可以使用一些实用程序类来生成这样的键 - 如 ValueKey()、UniqueKey 等。或者,如果您的数据中有它,您可以使用自己的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.