Flutter:如何在列表视图中通过拖放对项目进行排序?
Posted
技术标签:
【中文标题】Flutter:如何在列表视图中通过拖放对项目进行排序?【英文标题】:Flutter: How to sort items by drag and drop in the list view? 【发布时间】:2021-08-05 03:09:23 【问题描述】:我有一个颤振应用程序,该应用程序在列表视图中有一个记录列表,我希望用户能够使用拖放方法重新排序。所以我想在列表视图中使用拖放功能对项目进行重新排序。我该怎么做?
我想做这样的事情
【问题讨论】:
【参考方案1】:为此,您可以使用ReorderableListView
可重新排序的List是一个项目是可拖动的,用户可以重新排列/修改对象。
ReorderableListview
包含 childred、header、onReorder、scrollDirection 等属性...
children:我们会将列表项加载到此属性中
children: <Widget>[
for (int index = 0; index < _items.length; index++)
ListTile(
key: Key('$index'),
tileColor: _items[index].isOdd ? oddItemColor : evenItemColor,
title: Text('Item $_items[index]'),
),
],
onReorder:这是我们将处理拖动的列表项的属性
onReorder: (int oldIndex, int newIndex)
setState(()
if (oldIndex < newIndex)
newIndex -= 1;
final int item = _items.removeAt(oldIndex);
_items.insert(newIndex, item);
);
,
完整示例
class MyStatefulWidget extends StatefulWidget
const MyStatefulWidget(Key? key) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget>
final List<int> _items = List<int>.generate(50, (int index) => index);
@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(
padding: const EdgeInsets.symmetric(horizontal: 40),
children: <Widget>[
for (int index = 0; index < _items.length; index++)
ListTile(
key: Key('$index'),
tileColor: _items[index].isOdd ? oddItemColor : evenItemColor,
title: Text('Item $_items[index]'),
),
],
onReorder: (int oldIndex, int newIndex)
setState(()
if (oldIndex < newIndex)
newIndex -= 1;
final int item = _items.removeAt(oldIndex);
_items.insert(newIndex, item);
);
,
);
【讨论】:
以上是关于Flutter:如何在列表视图中通过拖放对项目进行排序?的主要内容,如果未能解决你的问题,请参考以下文章
WPF 中的 ItemsControl 是不是有一个好的解决方案,可以通过垂直拖放对其元素进行重新排序? [关闭]