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

Timer.periodic与Timer.cancel使用问题:无法正常取消定时器

解决Timer.periodic无法调用cancel的问题(报错Instance member 'cancel' can't be accessed using static access)

问题原因

  • cancel()是Timer实例的成员方法,不能通过Timer.cancel()这种静态方式调用,你当前的写法属于错误的静态访问。
  • 原代码没有保存Timer.periodic返回的定时器实例,导致需要取消时无法引用到对应的定时器对象。

修正方案

  1. 在合适的作用域(比如类成员位置)声明一个可空的Timer变量,用来保存定时器实例。
  2. 调用Timer.periodic时,将返回值赋值给这个变量。
  3. 需要取消定时器时,通过该变量调用cancel()方法,同时置空变量避免内存泄漏。

修正后的代码

// 在类中声明Timer变量(如果是Flutter State类,放在State成员位置)
Timer? _checkTimer;

void checking() {
  // 保存Timer实例到变量
  _checkTimer = Timer.periodic(const Duration(seconds: 1), (check) async {
    try {
      var url = Uri.parse('https://konamicash.com/verification_cron');
      var response = await http.get(url);
      print(response.statusCode);
      print('get no');
      if (response.statusCode == 200) {
        var reponse = jsonDecode(response.body);
        var message = reponse['situation'];
        print(message);
        print(reponse);
        if (message == 1) {
          // 通过实例调用cancel取消定时器
          _checkTimer?.cancel();
          _checkTimer = null;
        }
      }
    } catch (e) {
      print('erreur $e');
      // 出错时可按需取消定时器
      _checkTimer?.cancel();
      _checkTimer = null;
    }
  });
}

额外注意事项

如果是在Flutter的State类中使用,务必在页面销毁时取消定时器,防止内存泄漏:

@override
void dispose() {
  _checkTimer?.cancel();
  super.dispose();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 16:49:54