ReorderableListView: Managing List Order with ChangeNotifierProvider Package
In Flutter, building interactive and dynamic user interfaces is a breeze, thanks to its rich widget library. One such widget that comes in handy while building list-based UIs is the ReorderableListView.
What is ReorderableListView?
The ReorderableListView is a scrollable, touch-drag enabled list that allows users to change the order of its items. Under the hood, it leverages the GestureDetector and Draggable widgets to make reordering a seamless experience.
Why ChangeNotifierProvider Package?
When working with ReorderableListView, managing the list order becomes crucial. Here's where the ChangeNotifierProvider package comes into play. It helps in building a clean and maintainable architecture for managing the list order state.
Using ReorderableListView with ChangeNotifierProvider
To use the ReorderableListView with ChangeNotifierProvider, follow these steps:
-
First, add the
providerpackage to yourpubspec.yamlfile:dependencies: flutter: sdk: flutter provider: ^6.0.1 -
Create a model class that extends
ChangeNotifier:class ListOrderModel extends ChangeNotifier { List_itemOrder = [0, 1, 2]; List get itemOrder => _itemOrder; void reorder(int oldIndex, int newIndex) { if (oldIndex < newIndex) { newIndex -= 1; } final int item = _itemOrder.removeAt(oldIndex); _itemOrder.insert(newIndex, item); notifyListeners(); } } -
Use the
ChangeNotifierProviderandReorderableListViewin your widget tree:void main() { runApp( ChangeNotifierProvider( create: (context) => ListOrderModel(), child: MyApp(), ), ); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: Text('Reorderable ListView Example'), ), body: ReorderableListView( onReorder: (int oldIndex, int newIndex) { Provider.of(context, listen: false).reorder(oldIndex, newIndex); }, children: [ for (int i = 0; i < Provider.of (context).itemOrder.length; i++) ListTile( key: ValueKey(Provider.of (context).itemOrder[i]), title: Text('Item ${Provider.of (context).itemOrder[i]}'), ), ], ), ), ); } }
List Sub-widgets Manipulation
Inside the ListTile widget, you can add other widgets according to your needs. Changing these widgets' appearance does not affect the reordering feature, making ReorderableListView a versatile option for various use cases.
Summary & References
- ReorderableListView – Flutter documentation
- provider – A ChangeNotifierProvider package for state management