ReorderableListView - Reorder ListView Items using Drag and Drop in Flutter

This Article is posted by seven.srikanth at 8/23/2019 5:58:13 AM



In this example, I'm going to share the code on how to reorder a listview item.  
By using ReorderableListView widget, you can reorder the items inside a ListView. 
You need to observe that after dragging and dropping the item. We are calling a method to reorder the actual items in the List.
Here is how the final output is going to look.
Here is the full code from main.dart file. You can simply copy-paste and run the code to see the output.


import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  double padValue = 0;
  List<Paint> paints = [
    Paint(1'Red'Colors.red),
    Paint(2'Blue'Colors.blue),
    Paint(3'Green'Colors.green),
    Paint(4'Lime'Colors.lime),
    Paint(5'Indigo'Colors.indigo),
    Paint(6'Yellow'Colors.yellow)
  ];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("ReorderableListView Example"),
        ),
        body: ReorderableListView(
          children: List.generate(paints.length, (index) {
            return ListTile(
              key: ValueKey("value$ index "),
              leading: Container(
                width: 100.0,
                height: 100.0,
                color: paints[index].colorpicture,
              ),
              title: Text('ID: ' + paints[index].id.toString()),
              subtitle: Text(paints[index].title),
            );
          }),
          onReorder: (int oldIndex, int newIndex) {
            setState(() {
              _updateMyItems(oldIndex, newIndex);
            });
          },
        ),
      ),
    );
  }
  void _updateMyItems(int oldIndex, int newIndex) {
    if (newIndex > oldIndex) {
      newIndex -= 1;
    }
    final Paint item = paints.removeAt(oldIndex);
    paints.insert(newIndex, item);
  }
}
class Paint {
  final int id;
  final String title;
  final Color colorpicture;
  Paint(this.id, this.title, this.colorpicture);
}
Thanks, 
Srikanth

Tags: ReorderableListView - Reorder ListView Items in Flutter








0 Comments
Login to comment.
Recent Comments

Be the first to Comment. You can ask a Query or Share your toughts or Just say thanks.


© 2018 - Fluttercentral | Email to me - seven.srikanth@gmail.com