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

Flutter页面打开时启动计时器的实现问题

Flutter 跳转新页面同步启动计时器并显示计数

直接上可运行的实现方案:

1. 主页面代码(触发跳转)

import 'package:flutter/material.dart';
import 'timer_page.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Timer Demo',
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('主页面')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const TimerPage()),
            );
          },
          child: const Text('打开计时器页面'),
        ),
      ),
    );
  }
}

2. 计时器页面代码(启动并显示计数)

新建timer_page.dart文件:

import 'dart:async';
import 'package:flutter/material.dart';

class TimerPage extends StatefulWidget {
  const TimerPage({super.key});

  @override
  State<TimerPage> createState() => _TimerPageState();
}

class _TimerPageState extends State<TimerPage> {
  int _count = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    // 页面初始化时启动每秒触发的计时器
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _count++;
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('计时器页面')),
      body: Center(
        child: Text(
          '当前计数:$_count',
          style: const TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

核心逻辑说明

  • 跳转后TimerPage的initState方法会自动执行,在这里启动计时器刚好实现“跳转同步启动”的需求。
  • 用Timer.periodic创建周期性计时器,每秒更新计数并通过setState刷新UI。
  • 必须在dispose中取消计时器,避免页面销毁后计时器持续运行导致内存泄漏。

内容的提问来源于stack exchange,提问作者Ata Berk Çinetçi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:27:22