如何自定义ReorderableListView长按触发拖拽的灵敏度?
自定义ReorderableListView长按拖拽触发时长的解决方案
你可以通过ReorderableDelayedDragStartListener的delayedDuration参数自定义长按触发拖拽的时长,无需自己实现复杂的手势逻辑。
默认情况下ReorderableDelayedDragStartListener的延迟是Flutter内置的kLongPressTimeout(500毫秒),你可以直接传入Duration(milliseconds: 自定义时长)来调整到合适的触发速度。
修改后的代码示例:
@override Widget build(BuildContext context) { final ColorScheme colorScheme = Theme.of(context).colorScheme; final Color oddItemColor = colorScheme.primary.withOpacity(0.05); final Color evenItemColor = colorScheme.primary.withOpacity(0.15); return ReorderableListView( buildDefaultDragHandles: false, onReorder: (oldIndex, newIndex) { // 补充列表重排逻辑 if (newIndex > oldIndex) newIndex--; final item = _items.removeAt(oldIndex); _items.insert(newIndex, item); setState(() {}); }, children: <Widget>[ for (int index = 0; index < _items.length; index++) Container( key: Key('container-$index'), // 确保每个子项key唯一,避免与内部组件重复 color: index % 2 == 0 ? evenItemColor : oddItemColor, child: SizedBox( width: MediaQuery.of(context).size.width, height: 64, child: ReorderableDelayedDragStartListener( index: index, // 自定义长按触发时长为300毫秒,可根据需求调整 delayedDuration: const Duration(milliseconds: 300), child: ListTile( title: Text('Item ${_items[index]}'), ), ), ), ), ], ); }
注意事项:
- 必须保证
ReorderableListView的每个子项拥有唯一的key,避免和内部组件的key冲突 - 不要遗漏实现
onReorder回调,否则拖拽后列表不会发生实际排序变化
内容的提问来源于stack exchange,提问作者David Somekh
相关产品推荐
相关产品推荐

