如何在Flutter中运行时按位置添加小部件?

3

我试图在图片的点击位置添加一个按钮。 通过使用onTapUp的detail参数,我已经成功获取了点击位置。

然而,当用户点击图片时,我无法添加图标按钮。

下面的代码展示了我的示例。

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);
          },
        );          
  }
}

我试图在列表上添加按钮,但没有成功。
1个回答

4

所以,你错过了几件事情。 首先,你不能更新StatelessWidget的状态,因此需要使用StatefulWidget

其次,在使用StatefulWidget时,您需要调用setState来更新状态。您还需要使用Stack和Positioned小部件将按钮放置在特定位置上。您的代码应该像这样结束和看起来:

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,
    );
  }
}

谢谢!那个完美地解决了除了一个功能。我还需要将按钮放置在图像的偏移位置上,就像我在上面的问题中提到的那样。对此有什么评论吗? - hhk
更新了我的回答。 - hacksy
完美,谢谢!您的回答非常清晰,我理解了要点。谢谢! - hhk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接