Created
September 15, 2019 16:22
-
-
Save agiletelescope/db4c999b2923b5b11caed91c8d89f3a5 to your computer and use it in GitHub Desktop.
Flutter Reorderable ListView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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