import 'dart:async'; import 'package:flutter/widgets.dart'; /// One minute clock shared by every relative-time label. /// /// A list of rows used to run one timer per row; this clock runs a single /// timer, aligned to the start of each wall-clock minute, only while some /// label listens and the app is visible. Labels re-read [now] when it /// notifies and rebuild only if their text changed. class RelativeTimeClock extends ChangeNotifier with WidgetsBindingObserver { RelativeTimeClock(); /// The clock the app's labels share. static final RelativeTimeClock shared = RelativeTimeClock(); DateTime _now = DateTime.now(); Timer? _timer; bool _observing = false; bool _hidden = false; /// The clock's current minute-resolution time. It advances by the elapsed /// delay on each tick, which keeps it consistent under a fake clock. DateTime get now => _now; /// Whether a tick is scheduled (a label listens and the app is visible). @visibleForTesting bool get ticking => _timer != null; @override void addListener(VoidCallback listener) { final first = !hasListeners; super.addListener(listener); if (!first) return; _now = DateTime.now(); _hidden = switch (WidgetsBinding.instance.lifecycleState) { AppLifecycleState.hidden || AppLifecycleState.paused || AppLifecycleState.detached => true, _ => false, }; if (!_observing) { WidgetsBinding.instance.addObserver(this); _observing = true; } _schedule(); } @override void removeListener(VoidCallback listener) { super.removeListener(listener); if (hasListeners) return; _stop(); if (_observing) { WidgetsBinding.instance.removeObserver(this); _observing = false; } } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { _hidden = false; _now = DateTime.now(); notifyListeners(); _schedule(); } else if (state == AppLifecycleState.hidden || // Not inactive: a desktop window that lost focus is still visible. state == AppLifecycleState.paused || state == AppLifecycleState.detached) { _hidden = true; _stop(); } } void _schedule() { _timer?.cancel(); _timer = null; if (_hidden || !hasListeners) return; final intoMinute = Duration( seconds: _now.second, milliseconds: _now.millisecond, microseconds: _now.microsecond, ); final delay = const Duration(minutes: 1) - intoMinute; _timer = Timer(delay, () { _timer = null; _now = _now.add(delay); notifyListeners(); _schedule(); }); } void _stop() { _timer?.cancel(); _timer = null; } @override void dispose() { _stop(); if (_observing) WidgetsBinding.instance.removeObserver(this); super.dispose(); } }