You need to enable JavaScript to run this app. Flutter如何实现每隔5秒打印计时值、用户离开页面时触发打印
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何实现每隔5秒打印计时值、用户离开页面时触发打印

Flutter 计时打印优化方案

原有代码频繁打印的核心原因是将print逻辑写在了Countup组件的build方法中,AnimatedWidget会监听动画的每一次帧刷新触发重绘,Flutter默认每秒刷新60帧,所以会出现每秒多次打印的问题。

实现思路

  • 把打印逻辑从组件build方法中移除,统一放到页面State层管理
  • 给动画控制器添加监听,判断当前计时秒数与上次打印秒数的差值,达到5秒就触发打印
  • 在页面State的dispose生命周期(对应页面导航离开销毁)中获取当前计时值,打印停留时长

修改后完整代码

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: TimerTest(),
    );
  }
}

class TimerTest extends StatefulWidget {
  @override
  _TimerTestState createState() => _TimerTestState();
}

class _TimerTestState extends State<TimerTest> with TickerProviderStateMixin {
  AnimationController _controller;
  final int levelClock = 5400;
  // 记录上一次打印的秒数
  int _lastPrintedSecond = 0;

  @override
  void dispose() {
    // 页面离开时打印总停留时长
    final currentSecond = (_controller.value * levelClock).round();
    final clockTimer = Duration(seconds: currentSecond);
    final timerText =
        '${clockTimer.inMinutes.remainder(60)}:${clockTimer.inSeconds.remainder(60).toString().padLeft(2, '0')}';
    print('页面导航离开,总停留时长:$timerText');
    
    _controller.dispose();
    super.dispose();
  }

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

    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: levelClock),
    );

    // 添加动画监听处理5秒打印逻辑
    _controller.addListener(() {
      final currentSecond = (_controller.value * levelClock).round();
      // 距离上次打印满5秒则触发打印
      if (currentSecond - _lastPrintedSecond >= 5) {
        _lastPrintedSecond = currentSecond;
        final clockTimer = Duration(seconds: currentSecond);
        final timerText =
            '${clockTimer.inMinutes.remainder(60)}:${clockTimer.inSeconds.remainder(60).toString().padLeft(2, '0')}';
        print('当前计时耗时:$timerText');
      }
    });

    _controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xff04072E),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Countup(
              animation: StepTween(
                begin: 0,
                end: levelClock,
              ).animate(_controller),
            ),
          ],
        ),
      ),
    );
  }
}

class Countup extends AnimatedWidget {
  const Countup({Key key, this.animation}) : super(key: key, listenable: animation);
  final Animation<int> animation;

  @override
  build(BuildContext context) {
    final clockTimer = Duration(seconds: animation.value);

    final timerText =
        '${clockTimer.inMinutes.remainder(60)}:${clockTimer.inSeconds.remainder(60).toString().padLeft(2, '0')}';

    return Text(
      timerText,
      style: TextStyle(
        fontSize: 45,
        color: Theme.of(context).primaryColor,
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 00:45:07