Draggable Widget - Flutter Widget Guide By Flutter Agency

Draggable Widget – Flutter Widget Guide By Flutter Agency

What is the Draggable Widget in Flutter?

Draggable Widget allows a widget to be dragged, a DragTarget provides a destination for the draggable. A widget that can be dragged from to a DragTarget. 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.

It will give an ability to drag the child widget and you can control what you need to do when dragging the widget. It has a property to hold the data they represent.

The Default Constructor of it will have a code snippet like below :

Draggable({
  Key? key,
  required Widget child,
  required Widget feedback,
  Object? data,
  Axis? axis,
  Widget? childWhenDragging,
  Offset feedbackOffset = Offset.zero,
  Offset Function(Draggable<Object>, BuildContext, Offset) dragAnchorStrategy = childDragAnchorStrategy,
  Axis? affinity,
  int? maxSimultaneousDrags,
  void Function()? onDragStarted,
  void Function(DragUpdateDetails)? onDragUpdate,
  void Function(Velocity, Offset)? onDraggableCanceled,
  void Function(DraggableDetails)? onDragEnd,
  void Function()? onDragCompleted,
  bool ignoringFeedbackSemantics = true,
  bool ignoringFeedbackPointer = true,
  bool rootOverlay = false,
  HitTestBehavior hitTestBehavior = HitTestBehavior.deferToChild,
  bool Function(int)? allowedButtonsFilter,
})

In the Above constructor, all fields marked with @required must not be empty. The following code, snippet shows how to use Draggable.

Draggable(
child:// To do,
feedback: // To do,
)

Properties :

  • child: child Widget which can be dragged or to is displayed when draggable is stationary.
  • feedback: Widget to be displayed when drag is underway.
  • childWhenDragging: Widget to be displayed in the original place of Draggable when drag is underway.
  • data: It contains the information dropped by Draggable at DragTarget, it is useful when we are using multiple Draggable and DragTarget.

Draggable Properties :

  • onDragStarted(): onDragStarted() is called when the Draggable widget starts to drag.
  • onDragCompleted(): onDragCompleted() is called when Draggable is dropped on DropTarget and DropTarget has accepted the Draggable.
  • onDragEnd(): onDragEnd() is called when Draggable is dropped on DropTarget. This contains the velocity and Offset of Draggable when it was dropped.
  • onDraggableCancelled(): onDraggableCancelled is called when Draggable is dropped but not accepted by DragTarget.

How to use Draggable Widget in Flutter?

The following code snippet tells us how to implement a Draggable Widget in Flutter.

Draggable(
            feedback: Container(
              color: Colors.green,
              width: width,
              height: height,
              child: Center(
                child: Text(
                  "Drag To",
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        fontSize: 18,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                ),
              ),
            ),
            onDragStarted: () {
              print("onDragStarted");
            },
            onDragCompleted: () {
              print("onDragCompleted");
            },
            onDraggableCanceled: (Velocity velocity, Offset offset) {
              setState(() => position = offset);
            },
            child: Container(
              width: 100,
              height: 100,
              color: Colors.orangeAccent,
              child: Center(
                child: Text(
                  "Drag Me",
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        fontSize: 18,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                ),
              ),
            ),
          ),
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Material App Bar'),
        ),
        body: const SizeTransitionWidget(),
      ),
    );
  }
}

class SizeTransitionWidget extends StatefulWidget {
  const SizeTransitionWidget({super.key});

  @override
  _SizeTransitionWidgetState createState() => _SizeTransitionWidgetState();
}

class _SizeTransitionWidgetState extends State<SizeTransitionWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    )..repeat(reverse: true);
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: DraggableWidget(),
    );
  }
}

class DraggableWidget extends StatefulWidget {
  @override
  _DraggableWidgetState createState() => _DraggableWidgetState();
}

class _DraggableWidgetState extends State<DraggableWidget> {
  double width = 100.0, height = 100.0;
  late Offset position;

  @override
  void initState() {
    super.initState();
    position = Offset(0.0, height - 20);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Positioned(
          left: position.dx,
          top: position.dy - height + 20,
          child: Draggable(
            feedback: Container(
              color: Colors.green,
              width: width,
              height: height,
              child: Center(
                child: Text(
                  "Drag To",
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        fontSize: 18,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                ),
              ),
            ),
            onDragStarted: () {
              print("onDragStarted");
            },
            onDragCompleted: () {
              print("onDragCompleted");
            },
            onDraggableCanceled: (Velocity velocity, Offset offset) {
              setState(() => position = offset);
            },
            child: Container(
              width: 100,
              height: 100,
              color: Colors.orangeAccent,
              child: Center(
                child: Text(
                  "Drag Me",
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        fontSize: 18,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

We will get output like below :

Draggable Widget - Flutter Widget Guide By Flutter Agency

Draggable in Flutter

Conclusion:

In this article, we have been through What is Draggable Widget in Flutter along with how to implement it in a Flutter.

Thanks for reading.
In the next article, we get into DragTarget Widget. We are super excited to get into it like you.

Do let us know your suggestion/Feedback.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields