首页 > 解决方案 > 如何防止多次单击手势?

问题描述

我有一个需要启动 url 的 GestureDetector。但如果手势获得多次点击,则启动会被多次调用。

在当前代码中,我试图使用状态 _isButtonTapped 来控制点击。但是 .whenComplete 在启动之前以某种方式调用?

   _isButtonTapped = false

   Widget _buildButton(String key, Text title, String url) {
    _onTapped() async {
      if (await canLaunch(url)) {
        launch(url).whenComplete(
          () => setState(() {
                _isButtonTapped = false;
              }),
        );
      }
    }

    return GestureDetector(
      onTap: () {
        _isButtonTapped ? null : _onTapped();
        setState(() {
          _isButtonTapped = true;
        });
      },
      child: Container(
        child: Padding(
          padding: EdgeInsets.all(6.0),
          child: Center(child: title),
        ),
      ),
    );
  }

标签: flutterdart

解决方案


尝试这个:

class _HomePageState extends State<HomePage> {
  bool _isButtonTapped = false;
  String _url = "https://google.ca";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          color: Colors.blue,
          width: 100,
          height: 100,
          child: GestureDetector(
            onTap: () async {
              if (!_isButtonTapped) { // only allow click if it is false
                _isButtonTapped = true; // make it true when clicked
                if (await canLaunch(_url)) {
                  await launch(_url);
                  _isButtonTapped = false; // once url is launched successfully, we again make it false, allowing tapping again
                }
              }
            },
          ),
        ),
      ),
    );
  }
}

推荐阅读