cpd_2022_zi/lib/providers/timer_provider.dart

39 lines
874 B
Dart

import 'dart:async';
import 'package:flutter/material.dart';
class TimerProvider extends ChangeNotifier {
Timer? _timer;
bool started = false;
Duration _duration = const Duration();
int get elapsedSeconds => _duration.inSeconds;
int get elapsedMilliseconds => _duration.inMilliseconds;
final Duration _tickRate = const Duration(milliseconds: 20);
void startTimer(Duration duration) {
_duration = Duration.zero;
started = true;
_timer = Timer.periodic(_tickRate, ((timer) {
_duration += _tickRate;
if (elapsedSeconds >= duration.inSeconds) {
_timer?.cancel();
started = false;
}
notifyListeners();
}));
}
void stopTimer() {
started = false;
_timer?.cancel();
_timer = null;
_duration = Duration.zero;
}
@override
void dispose() {
stopTimer();
super.dispose();
}
}