Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draggable element with tracking x and y position in flutter

I am capturing an image and want to do some calculation on that image, for that I need to get the position of some spots on the image. For that, I am using the draggable element, my idea is to drag an element to spot on the image, get x and y position of the draggable elements to do calculations.

I have used the following code

body: Container(
        child: Stack(
          children: <Widget>[
            Image.file(File(widget.imagePath)),
            Draggable(
              axis: Axis.vertical,

              child: Text('_________', style: TextStyle(color: Colors.blue, fontSize: 90) ),
              feedback:Text('____',style: TextStyle(color: Colors.blue, fontSize: 90)) ,
              childWhenDragging: Text(''),

            ),

            SizedBox(height: 50.0,),

          ],
        ),
      )

Problem with this is 1. when an element is getting drag, that element position should move with touch, currently wile drag, element getting shifted by a few pixels. 2. Element position is not getting shifted to final drag position, when i remove touch element go back to original position.

Please help me with this.

like image 721
Ranjit singh Avatar asked Nov 18 '19 07:11

Ranjit singh


2 Answers

To use a Draggable like this,

  1. You'll need to be able to set the element's position, something like Positioned and its left,top.
  2. Then you'll need to get the ending coordinates of the drag, using dragDetails from onDragEnd: (dragDetails) { }

Here's a simple sample to start you off:

Positioned(
  left: _x,
  top: _y,
  child: Draggable(
    child: FlutterLogo(size: _logoSize),
    feedback: FlutterLogo(size: _logoSize),
    childWhenDragging: Container(),
    onDragEnd: (dragDetails) {
      setState(() {
        _x = dragDetails.offset.dx;
        // if applicable, don't forget offsets like app/status bar
        _y = dragDetails.offset.dy - appBarHeight - statusBarHeight;
      });
    },
  ),
)

enter image description here

Also a good intro to Draggable medium/A Deep Dive Into Draggable and DragTarget in Flutter

(if you don't want to use Draggable, you can also use a GestureDetector to accomplish the same thing, but a little more work)

like image 61
TWL Avatar answered Oct 07 '22 17:10

TWL


TWL's solution works, but do note that Positioned must be a descendent of a Stack widget.

like image 34
Tox Avatar answered Oct 07 '22 17:10

Tox