cover-img

Exploring the Draggable Widget in Flutter: Building Interactive Drag-and-Drop Experiences

Creating dynamic and engaging user interactions with the Draggable widget in Flutter

23 June, 2023

2

2

0

Introduction

In Flutter, the Draggable widget opens up a world of possibilities for creating interactive and intuitive user experiences. With its ability to handle drag-and-drop interactions, the Draggable widget empowers developers to build engaging features like reordering lists, draggable elements, and more. In this article, we'll dive into the power of the Draggable widget and explore how it can be implemented in your Flutter applications.

Understanding the Draggable Widget

The Draggable widget is a flexible tool that enables drag-and-drop functionality in your Flutter UI. It works by wrapping a child widget and providing it with a draggable behavior. When the user interacts with the draggable widget, it can be moved within its parent widget or even transferred to another widget, allowing for seamless and intuitive user interactions.

Implementing a Draggable List

Let's explore a practical example to demonstrate the capabilities of the Draggable widget. Imagine we have a to-do list, and we want users to be able to reorder the items by dragging them up or down. Here's how we can achieve this using the Draggable widget:

import 'package:flutter/material.dart';

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(50, (int index) => index);

  @override
  Widget build(BuildContext context) {
    final ColorScheme colorScheme = Theme.of(context).colorScheme;
    final Color oddItemColor = colorScheme.primary.withOpacity(0.05);
    final Color evenItemColor = colorScheme.primary.withOpacity(0.15);

    return ReorderableListView(
      padding: const EdgeInsets.symmetric(horizontal: 40),
      children: <Widget>[
        for (int index = 0; index < _items.length; index += 1)
          ListTile(
            key: Key('$index'),
            tileColor: _items[index].isOdd ? oddItemColor : evenItemColor,
            title: Text('Item ${_items[index]}'),
          ),
      ],
      onReorder: (int oldIndex, int newIndex) {
        setState(() {
          if (oldIndex < newIndex) {
            newIndex -= 1;
          }
          final int item = _items.removeAt(oldIndex);
          _items.insert(newIndex, item);
        });
      },
    );
  }
}

In the ReorderableExample widget, a list of integers, _items, is generated using the List.generate method. The length of the list is set to 50, and each item is assigned a unique index.

The build method sets up the UI using the ReorderableListView widget. It configures the padding and creates a list of ListTile widgets for each item in the _items list. Each ListTile is given a unique Key based on its index and a tile color based on whether the index is odd or even.

The onReorder callback is provided to handle the reordering logic. When an item is dragged and dropped to a new position, the callback is triggered. In the callback, the state is updated by removing the item from the old index and inserting it at the new index. The UI automatically reflects the updated order of items.

The ReorderableListView allows users to drag and reorder the list items based on their preferences, offering an interactive and intuitive user experience. This code provides a foundation for implementing draggable and reorderable lists in Flutter applications.

Output

Here's the output of the above code 👇

Conclusion:

The Draggable widget in Flutter provides a powerful tool for creating interactive drag-and-drop experiences in your applications. Whether it's reordering lists, implementing draggable elements, or enabling other drag-related features, the Draggable widget empowers developers to build dynamic and engaging user interactions. By harnessing the capabilities of the Draggable widget, you can take your Flutter apps to the next level and provide a delightful user experience.

Remember, the possibilities with the Draggable widget are endless, so feel free to experiment and explore its full potential in your Flutter projects. Happy coding!

draggablewidgetinflutter

reorderablelistview

draganddropinteractionsinflutter

2

2

0

draggablewidgetinflutter

reorderablelistview

draganddropinteractionsinflutter

Hasnain Makada
Elite @Showwcase | Prev: CCO @ShowwcaseHQ | Building out OSWH 👨‍💻 | MLSA - β | DevOps and Flutter 💙 | Blogger at Hashnode and Showwcase 📑

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.