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

Flutter页面切换时如何通过dispose禁用定时器?

问题解决:页面切换时取消Flutter定时器

核心问题分析

  1. 未保存Timer实例,导致无法在页面销毁时取消定时器
  2. dispose方法中错误调用startTimeout(),反而重复启动定时器,完全违背预期

修改后的完整代码

class _OutfitsMasterNewWidgetState extends State<OutfitsMasterNewWidget> {
  late FocusNode _searchFocus;
  late TextEditingController _searchController;
  final String? errorText = '';
  final interval = const Duration(seconds: 1);
  int currentSeconds = 0;
  Timer? _timer; // 新增:保存定时器实例

  String setStatus(int time) {
    if (time == 0) {
      return '0';
    } else {
      int timerMaxSeconds = time;
      if (timerMaxSeconds - currentSeconds <= 0) {
        _timer?.cancel(); // 倒计时结束自动取消定时器
        _timer = null;
        return '0';
      } else {
        return '${((timerMaxSeconds - currentSeconds) ~/ 60).toString().padLeft(2, '0')}: '
            '${((timerMaxSeconds - currentSeconds) % 60).toString().padLeft(2, '0')}';
      }
    }
  }

  void startTimeout() {
    var duration = interval;
    _timer = Timer.periodic(duration, (timer) {
      setState(() {
        currentSeconds = timer.tick;
      });
      // 可选:如果总秒数从widget传入,可在此判断取消
      // int totalSeconds = widget.totalSeconds;
      // if (currentSeconds >= totalSeconds) {
      //   timer.cancel();
      //   _timer = null;
      // }
    });
  }

  @override
  void initState() {
    _searchFocus = FocusNode();
    _searchController = TextEditingController();
    super.initState();
    startTimeout();
    BlocProvider.of<OutfitsNewBloc>(context).add(
      OutfitsNewInitialEvent(
        startInitial: true,
      ),
    );
  }

  @override
  void dispose() {
    _searchFocus.dispose();
    _searchController.dispose();
    _timer?.cancel(); // 页面销毁时强制取消定时器
    _timer = null; // 清空引用
    super.dispose();
  }
}

关键修改点

  • 新增Timer? _timer变量存储定时器实例,方便后续取消操作
  • 修改startTimeout(),将创建的Timer赋值给_timer
  • 在dispose()方法中调用_timer?.cancel(),确保页面销毁时定时器停止运行
  • 在倒计时结束的逻辑里也添加定时器取消,避免不必要的资源占用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:31:03