首页 > 解决方案 > 在屏幕上显示简单持续时间计时器

问题描述

有什么简单的方法可以在屏幕上显示 DURATION 中的剩余时间吗?

void onTapDown(TapDownDetails details){
        if(state == State.menu){
           timer = Timer(duration = new Duration(seconds: 5), () {
            state = State.playing;
           });
           print("STARTING IN [secondsremaing]");
        }

还是我应该让它变得复杂并实现任何其他类来这样做?

标签: flutterdartflutter-animation

解决方案


它不会那样工作,因为 aTimer只会在 given 之后调用给定的回调Duration,但它不会为你打勾
如果你想显示一个更新的小部件来指示剩余时间,你将不得不使用一个ticker,这通常是通过设置一个AnimationController.

在您的情况下,它可能看起来像这样(假设您在 a 中StatefulWidget):

class _YourWidgetsState extends State<YourWidget> with SingleTickerProviderMixin {
  AnimationController remainingTimeController;

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

    remainingTimeController = AnimationController(vsync: this, duration: const Duration(seconds: 5));
  }

  /// Used somewhere in your build method.
  void onTapDown(TapDownDetails details) {
    if(state == State.menu){
      timer = Timer(duration = new Duration(seconds: 5), () {
        state = State.playing;
      });
      print("STARTING IN [secondsremaing]");
    }
  }

  @override
  Widget build(BuildContext context) {
    // Obviously return your other widgets in here as well.

    return AnimatedBuilder(
      animation: remainingTimeController,
      builder: (context, _) => Text('${remainingTimeController.value * 60 * 5}'),
    );
  }
}

推荐阅读