You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Flutter电商项目中的onPressed修改为仅自动执行一次的函数

解决方案

你可以通过添加状态锁变量的方式实现回调仅单次执行,避免重复点击触发多次逻辑,具体实现步骤如下:

  • 第一步:在当前页面的State类中定义布尔类型的执行状态标记
class YourPageState extends State<YourPage> {
  // 新增执行状态锁,默认false代表未在执行逻辑
  bool _isProcessing = false;
  // 原有其他变量定义保留...
}
  • 第二步:修改原有onPressed回调逻辑,执行前先判断锁状态,执行过程中锁定,无论成功失败最终都要解锁避免锁永久失效

修改后的完整onPressed代码如下:

onPressed: _isProcessing ? null : () async {
  // 先上锁,拦截后续所有点击请求
  setState(() {
    _isProcessing = true;
  });
  try {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    await Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => Map(
                  latitude: latitude == null
                      ? position.latitude
                      : double.parse(latitude),
                  longitude: longitude == null
                      ? position.longitude
                      : double.parse(longitude),
                  from: getTranslated(context, 'ADDADDRESS'),
                )));
    if (mounted) setState(() {});
    List<Placemark> placemark = await placemarkFromCoordinates(
        double.parse(latitude), double.parse(longitude));

    state = placemark[0].administrativeArea;
    country = placemark[0].country;
    pincode = placemark[0].postalCode;
    //  address = placemark[0].name;
    if (mounted) {
      setState(() {
        countryC.text = country;
        stateC.text = state;
        pincodeC.text = pincode;
        // addressC.text = address;
      });
    }
  } catch (e) {
    // 可按需添加异常提示逻辑
    debugPrint('位置处理出错: $e');
  } finally {
    // 无论逻辑执行成功还是失败,最终都解锁
    if (mounted) {
      setState(() {
        _isProcessing = false;
      });
    }
  }
},

上述实现中执行逻辑过程中onPressed会被设为null,Flutter默认会将按钮置为不可点击状态,不需要额外修改按钮样式即可实现防重复点击效果,如有自定义禁用样式的需求,也可以通过_isProcessing变量动态配置按钮的style属性。

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:06:02