以下是使用Dart编写的计时器代码,其中包含一个取消函数:

import 'dart:async';

class TimerUtil {
  Timer _timer;
  int _seconds;
  bool _canceled = false;

  TimerUtil(this._seconds);

  void start() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(_canceled) {
        timer.cancel();
      } else {
        _seconds--;
        if(_seconds <= 0) {
          timer.cancel();
        }
      }
    });
  }

  void cancel() {
    _canceled = true;
  }
}

使用示例:

void main() {
  TimerUtil timer = TimerUtil(10);
  timer.start();

  // 取消计时器
  Future.delayed(Duration(seconds: 5), () => timer.cancel());
}
``
帮我用dart写一个计时器并且可以在外部取消

原文地址: https://www.cveoy.top/t/topic/ffUq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录