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

Flutter中定时器结束时自动切换页面的实现方法

Flutter番茄钟计时结束自动导航实现方案

一、检测计时器归零

在StartPomodoro页面的状态类中,通过定时器周期性更新剩余时间,每次更新后检查时间是否归零:

  • 维护一个剩余时间变量(如_remainingSeconds),初始化为番茄钟时长(比如25*60秒)
  • 使用Timer.periodic每秒更新剩余时间,每次回调中判断_remainingSeconds <= 0,一旦满足条件就停止定时器并触发导航。

二、计时结束后自动导航到StartShortBreak页面

利用Flutter的Navigator组件实现页面跳转,根据需求选择导航方式:

  • pushReplacement:替换当前页面,返回时不会回到番茄钟页面(适合番茄钟结束后直接进入休息,无需返回的场景)
  • push:将休息页面加入栈,返回时会回到番茄钟页面(适合需要手动返回继续计时的场景)

修改后的StartPomodoro核心代码示例

class StartPomodoroState extends State<StartPomodoro> {
  int _remainingSeconds = 25 * 60; // 默认25分钟番茄钟时长
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    startTimer();
  }

  void startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_remainingSeconds > 0) {
          _remainingSeconds--;
        } else {
          // 计时结束,清理定时器并跳转
          _timer?.cancel();
          _navigateToShortBreak();
        }
      });
    });
  }

  void _navigateToShortBreak() {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => const StartShortBreak()),
    );
    // 若需保留原页面栈,替换为以下代码:
    // Navigator.push(
    //   context,
    //   MaterialPageRoute(builder: (context) => const StartShortBreak()),
    // );
  }

  @override
  void dispose() {
    _timer?.cancel(); // 页面销毁时取消定时器,避免内存泄漏
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('番茄钟')),
      body: Center(
        child: Text(
          '${_remainingSeconds ~/ 60}:${(_remainingSeconds % 60).toString().padLeft(2, '0')}',
          style: const TextStyle(fontSize: 48),
        ),
      ),
    );
  }
}

注意事项

  • 无论使用原生Timer还是第三方倒计时插件,核心逻辑都是监听剩余时间变化,归零时触发导航
  • 确保调用Navigator时context处于有效状态(上述示例中定时器回调在页面构建完成后执行,context可用)
  • 必须在页面销毁时清理定时器,防止内存泄漏

内容的提问来源于stack exchange,提问作者pomoworko.com

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:24:20