Skip to content

Instantly share code, notes, and snippets.

@leighajarett
Last active June 16, 2023 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leighajarett/490a83543037c0decb430b0af0ab3f5c to your computer and use it in GitHub Desktop.
Save leighajarett/490a83543037c0decb430b0af0ab3f5c to your computer and use it in GitHub Desktop.
Reorderable list example
import 'package:flutter/material.dart';
/// Flutter code sample for [ReorderableListView].
void main() {
runApp(const ReorderableApp());
}
class ReorderableApp extends StatelessWidget {
const ReorderableApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ReorderableListView Sample')),
body: const ReorderableExample(),
),
);
}
}
class ReorderableExample extends StatefulWidget {
const ReorderableExample({super.key});
@override
State<ReorderableExample> createState() => _ReorderableListViewExampleState();
}
class _ReorderableListViewExampleState extends State<ReorderableExample> {
final List<int> _items = List<int>.generate(6, (int index) => index); // Generate 6 items for 6 colors
// Define a map of colors and their names
final Map<Color, String> _itemColors = {
Colors.red: 'Red',
Colors.orange: 'Orange',
Colors.yellow: 'Yellow',
Colors.green: 'Green',
Colors.blue: 'Blue',
Colors.purple: 'Purple',
};
@override
Widget build(BuildContext context) {
return ReorderableListView(
padding: const EdgeInsets.symmetric(horizontal: 40),
children: _items.map((int index) {
final Color itemColor = _itemColors.keys.toList()[index % _itemColors.length];
final String itemColorName = _itemColors[itemColor]!;
return ListTile(
key: Key('$index'),
tileColor: itemColor,
title: Text('$itemColorName item'),
);
}).toList(),
onReorder: (int oldIndex, int newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final int item = _items.removeAt(oldIndex);
_items.insert(newIndex, item);
});
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment