Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Get the local position from the GestureDetector

Tags:

flutter

I'm using the GestureDetector to get this events using:

onHorizontalDragStart: _onDragStart,
onHorizontalDragUpdate: _onDragUpdate,

But how can I transform the global position into local? The child that is moved is a Container.

like image 961
Razvan Cristian Lung Avatar asked Nov 13 '17 19:11

Razvan Cristian Lung


1 Answers

You can use a RenderObject and then transform the global positions into a local one similar to this simple example:

import "package:flutter/material.dart";

class Test extends StatefulWidget {
  @override
  _TestState createState() => new _TestState();
}

class _TestState extends State<Test> {
  _onDragStart(BuildContext context, DragStartDetails start) {
    print(start.globalPosition.toString());
    RenderBox getBox = context.findRenderObject();
    var local = getBox.globalToLocal(start.globalPosition);
    print(local.dx.toString() + "|" + local.dy.toString());
  }

  _onDragUpdate(BuildContext context, DragUpdateDetails update) {
    //print(update.globalPosition.toString());
    RenderBox getBox = context.findRenderObject();
    var local = getBox.globalToLocal(update.globalPosition);
    //print(local.dx.toString() + "|" + local.dy.toString());
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new GestureDetector(
          child: new Text("Drag"),
          onHorizontalDragStart: (DragStartDetails start) =>
              _onDragStart(context, start),
          onHorizontalDragUpdate: (DragUpdateDetails update) =>
              _onDragUpdate(context, update),
        ),
      ),
    );
  }
}
like image 65
Shady Aziza Avatar answered Nov 28 '22 18:11

Shady Aziza