How to add a widget by position on runtime in flutter?

Viewed 2963

I am trying to add a button on an image on tap position. I have managed to get position on tap by using onTapUp's detail parameter.

However, I can't add an icon button when user taps on the image.

Below code shows my sample.

class ArticlesShowcase extends StatelessWidget {
  final commentWidgets = List<Widget>();
  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
          child: new Center(
            child: Image.network(
              'https://via.placeholder.com/300x500',
            ),
          ),
          onTapUp: (detail) {
            final snackBar = SnackBar(
                content: Text(detail.globalPosition.dx.toString() +
                    " " +
                    detail.globalPosition.dy.toString()));
            Scaffold.of(context).showSnackBar(snackBar);
            new Offset(detail.globalPosition.dx, detail.globalPosition.dy);
            var btn = new RaisedButton(
              onPressed: () => {},
              color: Colors.purple,
              child: new Text(
                "Book",
                style: new TextStyle(color: Colors.white),
              ),
            );
            commentWidgets.add(btn);
          },
        );          
  }
}

I tried to add the button on the list but no chance.

1 Answers

So , there are a couple of things you are missing. First you can't update a StatelessWidget state , so you need to use a StatefulWidget.

Second, when using a StatefulWidget , you need to call setState to update the State. You will also need to use a Stack and Positioned widgets to put the buttons on your specific location. Your code should end and look like this.

class ArticlesShowcaseState extends State<ArticlesShowcase> {
  final commentWidgets = List<Widget>();
  void addButton(detail) {
    {
      final snackBar = SnackBar(
          content: Text(
              "${detail.globalPosition.dx.toString()} ${detail.globalPosition.dy.toString()}"));
      Scaffold.of(context).showSnackBar(snackBar);
      var btn = new Positioned(
          left: detail.globalPosition.dx,
          top: detail.globalPosition.dy,
          child: RaisedButton(
            onPressed: () => {},
            color: Colors.purple,
            child: new Text(
              "Book",
              style: new TextStyle(color: Colors.white),
            ),
          ));

      setState(() {
        commentWidgets.add(btn);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
            GestureDetector(
              child: new Center(
                child: Image.network(
                  'https://via.placeholder.com/300x500',
                ),
              ),
              onTapUp: (detail) => addButton(detail),
            )
          ] +
          commentWidgets,
    );
  }
}
Related