ReorderableListViewChildGlobalKey被多组件使用问题求助
解决ReorderableListView子项Key重复问题
你遇到的错误是因为ReorderableListView的直接子元素(即你封装的Dismissible组件)出现了重复Key,即便你已经基于item.rungId设置了Key,仍可能存在以下问题:
- 检查rungId的唯一性:先确认
_items列表中每个item.rungId是绝对唯一的,若存在重复的rungId,必然导致Key冲突。 - 显式指定Key类型:将Dismissible的Key从
Key(item.rungId)改为ValueKey(item.rungId),显式使用ValueKey可避免隐式类型转换潜在的问题,确保Key的唯一性更可靠。 - 替换index依赖的删除逻辑:你当前在
onDismissed中用index删除item,列表排序后index与item的对应关系会失效,可能引发状态异常进而导致Key问题。建议改为通过item本身删除:onDismissed: (direction) { setState(() { _items.remove(item); _removeditems.add(item); }); } - 排查列表更新逻辑:检查拖拽排序、删除恢复的代码,确保不会将同一个item重复添加到
_items中,重复的item会带来重复的rungId,进而引发Key重复。
修改后的_buildTenableListTile示例:
Widget _buildTenableListTile(Rung item, int index) { return Dismissible( key: ValueKey(item.rungId), onDismissed: (direction) { setState(() { _items.remove(item); _removeditems.add(item); }); }, background: Container(color: Colors.red), child: Padding( padding: const EdgeInsets.all(20.0), child: Card(child: cardWithInfoPage(item, context, index)), ), ); }
内容的提问来源于stack exchange,提问作者fluttergogo
相关产品推荐
相关产品推荐

