DragTarget Widget - Flutter Widget Guide By Flutter Agency

DragTarget Widget – Flutter Widget Guide By Flutter Agency

What is DragTarget Widget in Flutter?

DragTarget Widget is a widget that receives data when a Draggable widget is dropped. When a draggable is dragged on top of a drag target, the drag target is asked whether it will accept the data the draggable is carrying. If the user does drop the draggable on top of the drag target, then the drag target is asked to accept the draggable’s data.

DragTarget Widget means a widget which provides target or destination to Draggable Widget, it also receives the data from a Draggable. In other words, we can say that a DragTarget Widget provides a destination for the draggable.

The constructor for it will look like below :

DragTargetWidget({
Key key, 
@required DragTargetBuilder<T> builder, 
DragTargetWillAccept<T> onWillAccept, 
DragTargetAccept<T> onAccept, 
DragTargetLeave<T> onLeave,
 });

Here, also attribute marked with @required must not be empty.

Properties:

  • Key? key: An identifier for widgets, elements, and semantic nodes. It’s optional and used to control the framework’s widget replacement or retention in the widget tree.
  • required Widget Function(BuildContext, List<Object?>, List<dynamic>) builder: This is a required function that describes how to display the widget in terms of other, lower-level widgets. The builder function provides a context and two lists: one for candidate data being dragged over this target, and another for accepted data.
  • bool Function(Object?)? onWillAccept: An optional callback that decides whether an incoming draggable will be accepted. It takes the data being dragged and returns a boolean value.
  • bool Function(DragTargetDetails<Object>)? onWillAcceptWithDetails: Similar to onWillAccept, but it provides more details through DragTargetDetails, including the context and the offset where the draggable was dropped.
  • void Function(Object)? onAccept: An optional callback that is called when an accepted draggable is dropped over the target. It takes the data of the draggable.
  • void Function(DragTargetDetails<Object>)? onAcceptWithDetails: An extension of onAccept that provides additional details through DragTargetDetails.
  • void Function(Object?)? onLeave: An optional callback that’s called when a draggable that was previously hovering over the target leaves its area without being accepted.
  • void Function(DragTargetDetails<Object>)? onMove: An optional callback that’s called when an accepted draggable is moved over the target after being accepted but before being dropped.
  • HitTestBehavior hitTestBehavior = HitTestBehavior.translucent: Determines how the drag target behaves during hit testing. It defaults to HitTestBehavior.translucent, meaning that the widget will consider itself hit even if it’s transparent, allowing it to receive the draggable even when it doesn’t visually overlap with the drag target.

How to use DragTarget Widget in Flutter?

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

import 'package:flutter/material.dart';

class DragTargetWidget extends StatefulWidget {
  @override
  _DragTargetWidgetState createState() => _DragTargetWidgetState();
}

class _DragTargetWidgetState extends State<DragTargetWidget> {
  Color caughtColor = Colors.red;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        DragBox(
          Offset(0.0, 0.0),
          'Box 1',
          Colors.purple,
        ),
        DragBox(
          Offset(200.0, 0.0),
          'Box 2',
          Colors.orange,
        ),
        DragBox(
          Offset(300.0, 0.0),
          'Box 3',
          Colors.lightGreen,
        ),
        Positioned(
          left: 100.0,
          bottom: 0.0,
          child: DragTarget(
            onAccept: (Color color) {
              caughtColor = color;
            },
            builder: (
              BuildContext context,
              List<dynamic> accepted,
              List<dynamic> rejected,
            ) {
              return Container(
                width: 200.0,
                height: 200.0,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(28.0),
                  color: accepted.isEmpty ? caughtColor : Colors.grey.shade200,
                ),
                child: Center(
                  child: Text("Drag Here!"),
                ),
              );
            },
          ),
        )
      ],
    );
  }
}

class DragBox extends StatefulWidget {
  final Offset initPos;
  final String label;
  final Color itemColor;

  DragBox(
    this.initPos,
    this.label,
    this.itemColor,
  );

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

class DragBoxState extends State<DragBox> {
  Offset position = Offset(0.0, 0.0);

  @override
  void initState() {
    super.initState();
    position = widget.initPos;
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: position.dx,
      top: position.dy,
      child: Draggable(
        data: widget.itemColor,
        child: Container(
          width: 100.0,
          height: 100.0,
          color: widget.itemColor,
          child: Center(
            child: Text(
              widget.label,
              style: TextStyle(
                color: Colors.white,
                decoration: TextDecoration.none,
                fontSize: 20.0,
              ),
            ),
          ),
        ),
        onDraggableCanceled: (velocity, offset) {
          setState(() {
            position = offset;
          });
        },
        feedback: Container(
          width: 120.0,
          height: 120.0,
          color: widget.itemColor.withOpacity(0.5),
          child: Center(
            child: Text(
              widget.label,
              style: TextStyle(
                color: Colors.white,
                decoration: TextDecoration.none,
                fontSize: 18.0,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

The above code will give us output like below :

DragTarget Widget - Flutter Widget Guide By Flutter Agency

DragTarget Widget

Conclusion:

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

Thanks for being with us on a Flutter Journey.

Do leave us your valuable feedback so that we can serve you better.

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.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

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


ready to get started?

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

"*" indicates required fields

✓ Valid number ✕ Invalid number