Flutter实现List列表item拖动改变位置

先看效果吧:

Flutter实现List列表item拖动改变位置_第1张图片

喜欢上面的效果吗?实现代码如下:

import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(
    MaterialApp(
      home: HomePage(),
    )
);

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State {
  List list = List.generate(Random().nextInt(20)+10, (i) => 'More Item$i');

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('listview reorded'),
      ),
      body: Center(
        child: ReorderableListView(
            children: list
                .map((m) => ListTile(
                key: ObjectKey(m),
                title: Text(m),
            )).toList(),//不要忘记 .toList()
            onReorder: _onReorder,
        ),
      ),
    );
  }

  _onReorder(int oldIndex, int newIndex){
    print('oldIndex: $oldIndex , newIndex: $newIndex');
      setState(() {
        if (newIndex == list.length){
          newIndex = list.length - 1;
        }
        var item = list.removeAt(oldIndex);
        list.insert(newIndex, item);
      });
  }
}

以上就是代码实现了,快去试试吧。。。

你可能感兴趣的:(flutter,dart)