13、 Flutter Widgets 之 ReorderableListView拖拽排序组件

本文介绍了Flutter中的ReorderableListView组件,用于创建可以通过长按拖动来重新排序列表项的应用场景。它需要设置children和onReorder属性,其中children包含子控件,onReorder是拖动后的回调函数。每个子控件必须有唯一key,且不适合大量数据,适用于有限且需排序的集合。此外,还展示了如何设置header、reverse参数以及scrollDirection来定制列表行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ReorderableListView是通过长按拖动某一项到另一个位置来重新排序的列表组件。

ReorderableListView需要设置childrenonReorder属性,children是子控件,onReorder是拖动完成后的回调,用法如下:

  List<String> items = List.generate(40, (int i) => '$i');

ReorderableListView(
      children: <Widget>[
        for (String item in items)
          Container(
            key: ValueKey(item),
            height: 100,
            margin: EdgeInsets.symmetric(horizontal: 50, vertical: 10),
            decoration: BoxDecoration(
                color:
                Colors.primaries[int.parse(item) % Colors.primaries.length],
                borderRadius: BorderRadius.circular(10)),
            child: Text(item,style: TextStyle(fontSize: 30),textAlign: TextAlign.center,),
          )
      ],
      onReorder: (int oldIndex, int newIndex) {
        if (oldIndex < newIndex) {
          newIndex -= 1;
        }
        var child = items.removeAt(oldIndex);
        items.insert(newIndex, child);
        setState(() {

        });
      },
    )

长安子视图拖动效果:

 

ReorderableListView的每个子控件必须设置唯一的key,ReorderableListView没有“懒加载”模式,需要一次构建所有的子组件,所以ReorderableListView并不适合加载大量数据的列表,它适用于有限集合且需要排序的情况,比如手机系统里面设置语言的功能,通过拖动对语言排序。

onReorder是拖动完成的回调,第一个参数是旧的数据索引,第二个参数是拖动到位置的索引,回调里面需要对数据进行排序并通过setState刷新数据。

header参数显示在列表的顶部,用法如下:

ReorderableListView(
        header: Text(
          '一枚有态度的程序员',
          style: TextStyle(color: Colors.red,fontSize: 20),
          textAlign: TextAlign.center,
        ),
...
)

效果:

 reverse`参数设置为true且ReorderableListView的滚动方向为垂直时,滚动条直接滑动到底部,如果是水平方向则滚动条直接滑动到右边,默认为false,用法如下:

ReorderableListView(
  reverse: true,
  ...
)

 scrollDirection`参数表示滚动到方向,默认为垂直,设置为水平方向如下:

ReorderableListView(
  scrollDirection: Axis.horizontal,
  ...
)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风雨「83」

你的鼓励将是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值