【问题标题】:Flutter: How to sort items by drag and drop in the list view?Flutter:如何在列表视图中通过拖放对项目进行排序?
【发布时间】:2021-08-05 03:09:23
【问题描述】:

我有一个颤振应用程序,该应用程序在列表视图中有一个记录列表,我希望用户能够使用拖放方法重新排序。所以我想在列表视图中使用拖放功能对项目进行重新排序。我该怎么做?

我想做这样的事情

【问题讨论】:

    标签: flutter listview dart drag-and-drop draggable


    【解决方案1】:

    为此,您可以使用ReorderableListView

    可重新排序的List是一个项目是可拖动的,用户可以重新排列/修改对象。

    ReorderableListview 包含 childredheaderonReorderscrollDirection 等属性...

    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);
            });
          },
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-24
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 2011-03-09
      • 2018-01-25
      相关资源
      最近更新 更多