Open In App

Draggable Widget in Flutter

Last Updated : 06 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Flutter, a Draggable widget can be used to allow users to interact with a widget by dragging it around the screen. To create a Draggable widget, you can use the Draggable class and pass it to a child widget to be rendered, along with a feedback widget that will be displayed while the user is dragging the widget. The Draggable class also accepts various properties such as child, feedback, data, childWhenDragging, feedbackOffset to customize the draggable widget.

Example in the below video:

Now let’s learn how to implement this draggable widget.

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2:  Initialize the Draggable widget

  • Wrap the draggable widget in the column and give its Main and Cross alignment properties.
  • In the draggable widget, we have made a container giving it certain height and width, and color properties as well
  • Each Draggable should hold some data. DragTarget will use this data.

Output Image:

 

Step 3: Feedback Widget

The feedback widget is a required property of a draggable widget.

  • When a draggable widget recognizes the start of a drag gesture, it displays a feedback widget that tracks the user’s finger across the screen.
  • If the user lifts their finger while on top of a DragTarget, that target is given the opportunity to accept the data carried by the draggable.

For more understanding check the output below:

 

Here the orange box I am dragging on the screen is the Feedback Widget.

Step 4:  Using onDraggableCanceled

  • This is called when the item does not drop successfully or the user lifts their finger or mouse pointer
  • called when the draggable is dropped without being accepted by a DragTarget.

See the output for more understanding:

 

You can see in the video how drop is getting unsuccessful and onDraggableCanceled is working.

Step 5: Building DragTarget Widget

  • A widget that receives data when a Draggable widget is dropped.
  • DragTarget receives the Draggable widget; more specifically, it takes the data that is carried by the Draggable widget.
  • In drag target, we have a callback function called OnAccept. 
  • It is called when an acceptable piece of data is dropped over this drag target.
  • We have a builder function that is called to build the contents of this widget
  • We have made a container and given it height and width with the color property.

 

 

Complete Code:

Dart




import 'package:flutter/material.dart';
 
void main() {
    runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
    const MyApp({
        Key ? key
    }): super(key: key);
 
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
                primarySwatch: Colors.green,
            ),
            home: const MyHomePage(),
        );
    }
}
 
class MyHomePage extends StatefulWidget {
    const MyHomePage({
        Key ? key
    }): super(key: key);
    @override
    State < MyHomePage > createState() = > _MyHomePageState();
}
 
class _MyHomePageState extends State < MyHomePage > {
    Color caughtColor = Colors.red;
    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
                title: Text('GeeksforGeeks'),
                centerTitle: true,
            ),
            body: SizedBox(
                width: double.infinity,
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: < Widget > [
                        // Draggable Widget
                        Draggable(
                            data: Colors.orangeAccent,
                            child: Container(
                                width: 100,
                                height: 100,
                                color: Colors.orangeAccent,
                                child: const Center(
                                    child: Text('box'),
                                ),
                            ),
                            // calling onDraggableCanceled property
 
                            onDraggableCanceled: (velocity, offset) {},
                            feedback: Container(
                                width: 150,
                                height: 150,
                                color: Colors.orangeAccent.withOpacity(0.5),
                                child: const Center(
                                    child: Text(
                                        'Box...',
                                        style: TextStyle(
                                            color: Colors.white,
                                            decoration: TextDecoration.none,
                                            fontSize: 18.0,
                                        ),
                                    ),
                                ),
                            )
                        ),
 
                        // building Drag Target Widget
                        DragTarget(
                            onAccept: (Color color) {
                                caughtColor = color;
                            }, builder: (
                                BuildContext context,
                                List < dynamic > accepted,
                                List < dynamic > rejected,
                            ) {
                                return Container(
                                    width: 200,
                                    height: 200,
                                    color: accepted.isEmpty ? caughtColor : Colors.grey.shade200,
                                    child: const Center(
                                        child: Text('Drag here'),
                                    ),
                                );
                            }
                        )
                    ],
                ),
            ),
        );
    }
}


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads