Flutter列表项重排序插件reorderables的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter列表项重排序插件reorderables的使用

简介

reorderables 是一个Flutter包,它提供了多种可重排序(拖拽和放置)的组件,包括表格、行、列、Wrap布局以及Sliver列表。这些组件允许用户通过拖拽来改变子组件的顺序,并且只需要父组件提供一个 onReorder 函数来处理重新排序事件。

安装与配置

要使用 reorderables 包,请在项目的 pubspec.yaml 文件中添加依赖:

dependencies:
  reorderables: ^latest_version # 替换为最新的版本号

然后,在您的Dart文件中导入此包:

import 'package:reorderables/reorderables.dart';

使用示例

ReorderableSliverList 示例

class SliverExample extends StatefulWidget {
  @override
  _SliverExampleState createState() => _SliverExampleState();
}

class _SliverExampleState extends State<SliverExample> {
  List<Widget> _rows;

  @override
  void initState() {
    super.initState();
    _rows = List<Widget>.generate(
      50,
      (int index) => Text('This is sliver child $index', textScaleFactor: 2),
    );
  }

  @override
  Widget build(BuildContext context) {
    void _onReorder(int oldIndex, int newIndex) {
      setState(() {
        Widget row = _rows.removeAt(oldIndex);
        _rows.insert(newIndex, row);
      });
    }

    ScrollController _scrollController = PrimaryScrollController.of(context) ?? ScrollController();

    return CustomScrollView(
      controller: _scrollController,
      slivers: <Widget>[
        SliverAppBar(
          expandedHeight: 210.0,
          flexibleSpace: FlexibleSpaceBar(
            title: Text('ReorderableSliverList'),
            background: Image.network(
              'https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Yushan'
                  '_main_east_peak%2BHuang_Chung_Yu%E9%BB%83%E4%B8%AD%E4%BD%91%'
                  '2B9030.png/640px-Yushan_main_east_peak%2BHuang_Chung_Yu%E9%'
                  'BB%83%E4%B8%AD%E4%BD%91%2B9030.png',
            ),
          ),
        ),
        ReorderableSliverList(
          delegate: ReorderableSliverChildListDelegate(_rows),
          onReorder: _onReorder,
        )
      ],
    );
  }
}

ReorderableTable 示例

class TableExample extends StatefulWidget {
  @override
  _TableExampleState createState() => _TableExampleState();
}

class _TableExampleState extends State<TableExample> {
  List<ReorderableTableRow> _itemRows;

  @override
  void initState() {
    super.initState();
    var data = [
      ['Alex', 'D', 'B+', 'AA', ''],
      ['Bob', 'AAAAA+', '', 'B', ''],
      ['Cindy', '', 'To Be Confirmed', '', ''],
      ['Duke', 'C-', '', 'Failed', ''],
      ['Ellenina', 'C', 'B', 'A', 'A'],
      ['Floral', '', 'BBB', 'A', 'A'],
    ];

    Widget _textWithPadding(String text) {
      return Padding(
        padding: EdgeInsets.symmetric(vertical: 4),
        child: Text(text, textScaleFactor: 1.1),
      );
    }

    _itemRows = data.map((row) {
      return ReorderableTableRow(
        key: ObjectKey(row),
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          _textWithPadding('${row[0]}'),
          _textWithPadding('${row[1]}'),
          _textWithPadding('${row[2]}'),
          _textWithPadding('${row[3]}'),
        ],
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    var headerRow = ReorderableTableRow(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text('Name', textScaleFactor: 1.5),
        Text('Math', textScaleFactor: 1.5),
        Text('Science', textScaleFactor: 1.5),
        Text('Physics', textScaleFactor: 1.5),
        Text('Sports', textScaleFactor: 1.5)
      ]
    );

    void _onReorder(int oldIndex, int newIndex) {
      setState(() {
        ReorderableTableRow row = _itemRows.removeAt(oldIndex);
        _itemRows.insert(newIndex, row);
      });
    }

    return ReorderableTable(
      header: headerRow,
      children: _itemRows,
      onReorder: _onReorder,
    );
  }
}

ReorderableWrap 示例

class WrapExample extends StatefulWidget {
  @override
  _WrapExampleState createState() => _WrapExampleState();
}

class _WrapExampleState extends State<WrapExample> {
  final double _iconSize = 90;
  List<Widget> _tiles;

  @override
  void initState() {
    super.initState();
    _tiles = <Widget>[
      Icon(Icons.filter_1, size: _iconSize),
      Icon(Icons.filter_2, size: _iconSize),
      Icon(Icons.filter_3, size: _iconSize),
      Icon(Icons.filter_4, size: _iconSize),
      Icon(Icons.filter_5, size: _iconSize),
      Icon(Icons.filter_6, size: _iconSize),
      Icon(Icons.filter_7, size: _iconSize),
      Icon(Icons.filter_8, size: _iconSize),
      Icon(Icons.filter_9, size: _iconSize),
    ];
  }

  @override
  Widget build(BuildContext context) {
    void _onReorder(int oldIndex, int newIndex) {
      setState(() {
        Widget row = _tiles.removeAt(oldIndex);
        _tiles.insert(newIndex, row);
      });
    }

    var wrap = ReorderableWrap(
      spacing: 8.0,
      runSpacing: 4.0,
      padding: const EdgeInsets.all(8),
      children: _tiles,
      onReorder: _onReorder,
      onNoReorder: (int index) {
        debugPrint('${DateTime.now().toString().substring(5, 22)} reorder cancelled. index:$index');
      },
      onReorderStarted: (int index) {
        debugPrint('${DateTime.now().toString().substring(5, 22)} reorder started: index:$index');
      }
    );

    var column = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        wrap,
        ButtonBar(
          alignment: MainAxisAlignment.start,
          children: <Widget>[
            IconButton(
              iconSize: 50,
              icon: Icon(Icons.add_circle),
              color: Colors.deepOrange,
              padding: const EdgeInsets.all(0.0),
              onPressed: () {
                var newTile = Icon(Icons.filter_9_plus, size: _iconSize);
                setState(() {
                  _tiles.add(newTile);
                });
              },
            ),
            IconButton(
              iconSize: 50,
              icon: Icon(Icons.remove_circle),
              color: Colors.teal,
              padding: const EdgeInsets.all(0.0),
              onPressed: () {
                setState(() {
                  _tiles.removeAt(0);
                });
              },
            ),
          ],
        ),
      ],
    );

    return SingleChildScrollView(
      child: column,
    );
  }
}

ReorderableColumn 示例

class ColumnExample1 extends StatefulWidget {
  @override
  _ColumnExample1State createState() => _ColumnExample1State();
}

class _ColumnExample1State extends State<ColumnExample1> {
  List<Widget> _rows;

  @override
  void initState() {
    super.initState();
    _rows = List<Widget>.generate(
      50,
      (int index) => Text('This is row $index', key: ValueKey(index), textScaleFactor: 1.5),
    );
  }

  @override
  Widget build(BuildContext context) {
    void _onReorder(int oldIndex, int newIndex) {
      setState(() {
        Widget row = _rows.removeAt(oldIndex);
        _rows.insert(newIndex, row);
      });
    }

    return ReorderableColumn(
      header: Text('THIS IS THE HEADER ROW'),
      footer: Text('THIS IS THE FOOTER ROW'),
      crossAxisAlignment: CrossAxisAlignment.start,
      children: _rows,
      onReorder: _onReorder,
    );
  }
}

ReorderableRow 示例

class RowExample extends StatefulWidget {
  @override
  _RowExampleState createState() => _RowExampleState();
}

class _RowExampleState extends State<RowExample> {
  List<Widget> _items = [
    Container(width: 100, height: 100, color: Colors.red),
    Container(width: 100, height: 100, color: Colors.green),
    Container(width: 100, height: 100, color: Colors.blue),
  ];

  void _onReorder(int oldIndex, int newIndex) {
    setState(() {
      Widget item = _items.removeAt(oldIndex);
      _items.insert(newIndex, item);
    });
  }

  @override
  Widget build(BuildContext context) {
    return ReorderableRow(
      children: _items,
      onReorder: _onReorder,
    );
  }
}

总结

reorderables 插件为Flutter应用提供了丰富的拖拽重排功能,适用于多种场景下的UI设计需求。通过上述示例代码,开发者可以快速集成并自定义这些组件以满足实际项目中的要求。希望这篇指南对您有所帮助!

如果您有任何问题或需要进一步的帮助,请随时提问!


更多关于Flutter列表项重排序插件reorderables的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter列表项重排序插件reorderables的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,我可以为你提供一个关于如何在Flutter中使用reorderables插件来实现列表项重排序的示例代码。reorderables是一个用于实现列表项拖拽和重新排序的Flutter包。尽管这不是Flutter官方提供的包,但它在社区中非常受欢迎。

首先,确保你已经在pubspec.yaml文件中添加了reorderables依赖:

dependencies:
  flutter:
    sdk: flutter
  reorderables: ^x.y.z  # 替换为最新版本号

然后运行flutter pub get来安装依赖。

下面是一个完整的示例代码,展示如何使用reorderables插件来实现列表项的重排序功能:

import 'package:flutter/material.dart';
import 'package:reorderables/reorderables.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Reorderables Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<String> items = List<String>.generate(10, (i) => "Item ${i + 1}");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Reorderable List Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: ReorderableListView(
          onReorder: (oldIndex, newIndex) {
            setState(() {
              final String item = items.removeAt(oldIndex);
              items.insert(newIndex, item);
            });
          },
          children: List.generate(
            items.length,
            (index) {
              return ListTile(
                key: ValueKey(items[index]),
                title: Text(items[index]),
              );
            },
          ),
        ),
      ),
    );
  }
}

代码解释

  1. 依赖导入

    • import 'package:flutter/material.dart';
    • import 'package:reorderables/reorderables.dart';
  2. 应用入口

    • MyApp类是一个无状态小部件,它创建了应用的根MaterialApp
  3. 主页面

    • MyHomePage是一个有状态小部件,它持有列表项的状态。
    • items列表用于存储列表项的数据。
  4. 构建UI

    • Scaffold小部件包含了一个应用栏和一个填充了ReorderableListView的主体。
    • ReorderableListView是一个可重新排序的列表视图。它有两个主要参数:
      • onReorder:当列表项顺序改变时调用的回调。我们在这里更新items列表的顺序。
      • children:列表项,这里使用ListTile来展示每个列表项。
  5. 列表项重排序

    • 当用户拖动列表项时,onReorder回调会被触发,并传递旧索引和新索引。
    • 使用setState方法更新items列表的顺序,以反映新的排列。

运行这个示例代码,你将看到一个可重新排序的列表,你可以通过拖动列表项来改变它们的顺序。

希望这个示例能帮助你理解如何在Flutter中使用reorderables插件来实现列表项的重排序功能。

回到顶部