I'm trying to implement ReorderableListView in my Flutter app. The code is simple:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: MyHomePage()));
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _onReorder(int oldIndex, int newIndex) => setState(
() => items.insert(
newIndex > oldIndex ? newIndex -= 1 : newIndex,
items.removeAt(oldIndex),
),
);
var items = ['Item A', 'Item B', 'Item C'];
@override
Widget build(context) => Scaffold(
body: ReorderableListView(
onReorder: _onReorder,
children: items.map((item) {
var index = items.indexOf(item);
return ListTile(
key: Key('$index'),
tileColor: Colors.white,
title: Text(item),
onTap: () {
// Handle tap
},
);
}).toList(),
),
);
}
I can't make the code work. The items can't be reordered. flutter --version
command tells me:
Flutter 3.3.8 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 52b3dc25f6 (3 days ago) • 2022-11-09 12:09:26 +0800
Engine • revision 857bd6b74c
Tools • Dart 2.18.4 • DevTools 2.15.0
And flutter doctor
tells me:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.8, on macOS 13.0.1 22A400 darwin-x64, locale en-ID)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.3)
[✓] IntelliJ IDEA Ultimate Edition (version 2022.2.1)
[✓] VS Code (version 1.73.1)
[✓] Connected device (4 available)
[✓] HTTP Host Availability
• No issues found!
What is wrong with my code?
After many hours of trial and error with many samples and tutorials all over the internet, I have found the cause: In Flutter 3.x, ReorderableListView will only work if we use
ReorderableDragStartListener
. This is the 1 link that led me to the right direction: https://github.com/flutter/flutter/issues/114783. How to use the listener? I have to modify my code, and update theListTile
part as follows:I hope this answer will help people, and no one gets through all the frustrating hours like I did.