简体   繁体   中英

Flutter ReorderableListView example

Can anyone show how to make this?

在此处输入图片说明

You can use this code.

class _HomePageState extends State<HomePage> {
  List<String> _list = List.generate(5, (i) => "${i}");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: ReorderableListView(
        padding: EdgeInsets.symmetric(horizontal: 40),
        children: _list.map((String string) => ListTile(key: Key(_list[_list.indexOf(string)]), title: Text(string))).toList(),
        onReorder: (oldIndex, newIndex) {
          String old = _list[oldIndex];
          if (oldIndex > newIndex) {
            for (int i = oldIndex; i > newIndex; i--) {
              _list[i] = _list[i - 1];
            }
            _list[newIndex] = old;
          } else {
            for (int i = oldIndex; i < newIndex - 1; i++) {
              _list[i] = _list[i + 1];
            }
            _list[newIndex - 1] = old;
          }
          setState(() {});
        },
      ),
    );
  }
}

Another option, instead of directly adjusting index values:

 if (oldIndex < newIndex) {
   newIndex -= 1;
 }
 final int item = _items.removeAt(oldIndex);
 _items.insert(newIndex, item);

As can be seen in an example on https://api.flutter.dev/flutter/material/ReorderableListView-class.html .

Was trying to do this myself today. Was not satisfied with either answer. Here is what I came up with.

 ReorderableListView(
    padding: EdgeInsets.all(6),
    buildDefaultDragHandles: false,
    onReorder: (int oldIndex, int newIndex) {
       test.insert(newIndex, test[oldIndex]);
          if (oldIndex < newIndex) {
             test.removeAt(oldIndex);
          } else {
             test.removeAt(oldIndex + 1);
          }
             setState(() {});
    },
    children: test.asMap().entries.map((e) {
       return ReorderableDragStartListener(
       index: e.key,
       key: Key(e.key.toString() + e.value),
       child: AspectRatio(
          aspectRatio: 16 / 9,
          child: Card(
           child: Center(child: Text(e.value)),
            elevation: 4,
            ),
          ),
         );
       }).toList(),
    ),

It this avoids the unneeded loops in user6274128's answer, and doesn't have the bug in Scott's answer. It also avoids bugs with index being based on the List.indexof as that will return the first instance of the String instead of the correct one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM