How to get offset of a current widget

2019-05-07 13:00发布

问题:

I am trying to draw a widget whenever a user presses the screen. Currently I am doing this by storing a list of widgets and when ontapup is fired on the gesture i am adding to a list of widgets.

Widget build(BuildContext context) {
Widget draw = new Text("A");
List<Widget> children = new List<Widget>();
return new Scaffold(
  appBar: new AppBar(
    title: const Text('Heading'),
    leading: new Icon(Icons.question_answer),
  ),
  body: new GestureDetector(
    onTapUp: (details) {
      setState(() {
          children.add(new Positioned(
            left: details.globalPosition.dx,
            top: details.globalPosition.dy,
            child: draw,
          ));
         });
    },
    child: new Stack(children: children)
    ...

So my code is working I am drawing the widget when I click but my problem is that when adding the new Positioned() to stack the position is based on the screen which does not include the appbar offset. Is there a way to get the stacks initial x/y position? Or is there a way to get the appbars height? How do I get a widgets position or height/width?

回答1:

Ok for anyone else who has the same issue I needed to create my own widget and use

context.findRenderObject() 

and

globalToLocal()

Just FYI global to local did not work while in the one solution I needed to make it its own widget.



标签: dart flutter