如何解决Flutter StopWatch Stream没有停止
我为秒表创建了服务。
class StopWatchService {
String timetodisplay = '00:00:00';
Stopwatch swatch = Stopwatch();
final duration = const Duration(seconds: 1);
StreamController<String> stopWatchStreamController;
void startTimer() {
Timer(duration,keepRunning);
}
void keepRunning() {
if (swatch.isRunning) {
startTimer();
}
var hours = swatch.elapsed.inHours.toString().padLeft(2,"0");
var minutes = (swatch.elapsed.inMinutes % 60).toString().padLeft(2,"0");
var seconds = (swatch.elapsed.inSeconds % 60).toString().padLeft(2,"0");
timetodisplay = hours + ':' + minutes + ':' + seconds;
if (swatch.isRunning) {
stopWatchStreamController.add(timetodisplay);
}
else {
stopWatchStreamController.close();
}
// timeInSec = swatch.elapsed.inSeconds;
}
void start() {
swatch.start();
startTimer();
}
void stop() {
print('ride service stop ${swatch.isRunning}');
swatch.stop();
// stopWatchStreamController.close();
print('ride service stop 1 - ${swatch.isRunning}');
}
Stream<String> getStopWatchStream() {
stopWatchStreamController = StreamController<String>(
onListen: start,onCancel: stop,onResume: start,onPause: stop,);
return stopWatchStreamController.stream;
}
}
在我的mobx商店中,我已经添加了这些。
final RideService _rideService = RideService();
Stream<String> timerStream;
StreamSubscription<String> timerSubscription;
@observable
String movingTime;
@action
startTimer() {
timerStream = _rideService.getStopWatchStream();
timerSubscription = timerStream.listen((time) {
print('event - $time');
movingTime = time;
});
}
@action
stopTimer() {
print('stopTimer');
// _rideService.stop();
timerSubscription.cancel();
timerStream = null;
print('dsadsadadad ${timerSubscription}');
}
现在在小部件文件中,单击按钮时我正在调用startTimer,它工作正常。 但是当我在点击停止按钮时调用stopTimer时,计时器值仍在更新。
我不确定自己在做什么错。
谢谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。