You get the timer passed into the callback. You can just call cancel() on it:
Timer.periodic(const Duration(seconds: 1), (timer) {
if(condition) {
timer.cancel();
}
});
or
Timer timer;
startTimer() {
timer = Timer.periodic(const Duration(seconds: 1), (timer) {
if(condition) {
cancelTimer();
}
});
}
cancelTimer() {
timer.cancel();
}
this way the timer can be cancelled independent of a timer event.
Full non-nullable Dart example
import 'dart:async';
Timer? timer;
bool condition = false;
void main() async {
startTimer();
await Future.delayed(const Duration(milliseconds: 600), () => condition = true);
}
startTimer() {
timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
print("condition: ${condition}");
if (condition) {
cancelTimer();
}
});
}
cancelTimer() {
timer?.cancel();
timer = null;
}