Skip to content

Instantly share code, notes, and snippets.

@agiletelescope
Created September 15, 2019 16:22
Show Gist options
  • Save agiletelescope/db4c999b2923b5b11caed91c8d89f3a5 to your computer and use it in GitHub Desktop.
Save agiletelescope/db4c999b2923b5b11caed91c8d89f3a5 to your computer and use it in GitHub Desktop.
Flutter Reorderable ListView
import 'package:flutter/material.dart';
class QuestionsPage extends StatefulWidget {
@override
_QuestionsPageState createState() => _QuestionsPageState();
}
class _QuestionsPageState extends State<QuestionsPage> {
// List of items
List<String> data = [ "a", "b", "c" ];
@override
Widget build(BuildContext context) {
return Container(
child: new ReorderableListView(
children: data.map((i) => new ListTile(
key: new ObjectKey(i),
title: new Text(i),
subtitle: new Text(i),
)).toList(),
onReorder: (int oldIndex, int newIndex) {
// Check if the new index exceeds the length of the list
// If yes, decrement the new index by one
// This prevents list index out of range exception
if (newIndex > oldIndex) {
newIndex --;
}
// Finally, remove the item in the oldIndex and repopulate it in newIndex
setState(() {
String item = data.removeAt(oldIndex);
data.insert(newIndex, item);
});
}
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment