Timer callbacks are not a precise clock. A busy event loop or backgrounded application can delay them. Store a deadline and derive the remaining time from the current clock instead of subtracting exactly one second per callback.
A small countdown
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: FocusTimer()));
class FocusTimer extends StatefulWidget {
const FocusTimer({super.key});
@override
State<FocusTimer> createState() => _FocusTimerState();
}
class _FocusTimerState extends State<FocusTimer> {
Timer? ticker;
DateTime? deadline;
int remaining = 30;
void start() {
ticker?.cancel();
setState(() { remaining = 30; deadline = DateTime.now().add(const Duration(seconds: 30)); });
ticker = Timer.periodic(const Duration(milliseconds: 200), (_) {
final milliseconds = deadline!.difference(DateTime.now()).inMilliseconds;
final seconds = (milliseconds / 1000).ceil().clamp(0, 30).toInt();
if (mounted) setState(() => remaining = seconds);
if (seconds == 0) ticker?.cancel();
});
}
@override
void dispose() { ticker?.cancel(); super.dispose(); }
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('A moment to focus')),
body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
Text('$remaining', style: const TextStyle(fontSize: 64)),
FilledButton(onPressed: start, child: const Text('Start 30 seconds')),
])),
);
}Separate timing from refreshing
The deadline describes when the session ends. The periodic timer only asks the interface to refresh. If one callback is late, the next calculation still uses the actual time.
For a production app, decide how clock changes, background execution and notifications should work. A monotonic clock can be appropriate for elapsed-time measurement while wall-clock deadlines serve a different purpose.
Distinguish the clock from the refresh callback
The deadline represents when the session ends. The periodic callback merely asks the interface to recompute what remains. If one callback is late, the next update still compares the current time with the same deadline instead of assuming exactly one second passed.
Starting again cancels the old timer before scheduling another. Leaving the screen also cancels owned work. These are important behavior checks: repeated starts should not create multiple countdown loops.
For production timing, decide how backgrounding and wall-clock changes should behave. Review lifecycle ownership and the disposed-state diagnostic before adding pause, persistence or notification features.
Try it yourself
Add a stop action. Then add a session duration input and validate it before starting. Test starting twice quickly: there should still be only one active periodic timer.