flutter - 如何防止多次单击手势?
问题描述
我有一个需要启动 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),
),
),
);
}
解决方案
尝试这个:
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
}
}
},
),
),
),
);
}
}
推荐阅读
- android - 未经许可获取特定联系人的电子邮件地址
- python - Python for 循环复制和粘贴
- python - 我正在尝试使用 .update() 添加到 python 中的字典
- vba - 创建具有可变步长的 2 个数字之间的值列表
- c# - 如何使用 EF6 获取大量记录
- javascript - 防止 Bootstrap 5 Accordion 崩溃
- redirect - 如何使用 API 签名的一部分重定向和 API 调用
- java - 如何在准备好的语句中有条件地调用过程?
- matlab - 为什么使用MATPOWER中的Power Flow在线容量会低于发电量(实际)?
- javascript - Material UI 的 TableRow 不允许样式覆盖