itemExtent不为空时ReorderableList排序出现异常缩进的修复求助
问题原因
你遇到的是Flutter框架中ReorderableListView的已知bug,当组件设置水平滚动方向Axis.horizontal同时配置itemExtent参数时,内部计算拖拽元素的偏移量逻辑出错,会把水平的item宽度值错误代入垂直方向的缩进计算,导致拖动时出现异常偏移。
修复方案
方案一(最简便,优先推荐)
删除ReorderableListView的itemExtent参数,直接给子元素指定固定宽度即可,原需求的尺寸约束不会受影响:
@override Widget build(BuildContext context) { // 提前计算好每个item的宽度 final itemWidth = MediaQuery.of(context).size.width / 5; return ReorderableListView( scrollDirection: Axis.horizontal, children: <Widget>[ for (int index = 0; index < _items.length; index++) Container( // 直接给子元素设置固定宽度即可 width: itemWidth, height: double.infinity, key: Key('$index'), color: Colors.blue[200 + index % 5 * 100], child: Center(child: Text('${_items[index]}')), ), ], onReorder: (oldIndex, newIndex) { // 原有排序逻辑保持不变 if (newIndex > oldIndex) newIndex--; final item = _items.removeAt(oldIndex); _items.insert(newIndex, item); }, ); }
方案二(需要保留itemExtent时使用)
自定义proxyDecorator属性,手动修正拖拽时的偏移量:
@override Widget build(BuildContext context) { final itemWidth = MediaQuery.of(context).size.width / 5; return ReorderableListView( itemExtent: itemWidth, scrollDirection: Axis.horizontal, proxyDecorator: (child, index, animation) { return Transform.translate( // 手动抵消错误计算的垂直偏移量 offset: Offset(0, -itemWidth), child: child, ); }, children: <Widget>[ for (int index = 0; index < _items.length; index++) Container( width: double.infinity, height: double.infinity, key: Key('$index'), color: Colors.blue[200 + index % 5 * 100], child: Center(child: Text('${_items[index]}')), ), ], onReorder: (oldIndex, newIndex) {}, ); }
内容的提问来源于stack exchange,提问作者nazarpunk
相关产品推荐
相关产品推荐

