import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; class BeamClock extends ChangeNotifier implements ValueListenable { BeamClock._(); static final BeamClock instance = BeamClock._(); Ticker? _ticker; int _attachCount = 0; double _base = 0; double _value = 0; @override double get value => _value; @visibleForTesting bool get isRunning => _ticker != null; @visibleForTesting int get attachCount => _attachCount; void attach() { _attachCount++; if (_ticker == null) { _base = _value; _ticker = Ticker(_onTick)..start(); } } void detach() { if (_attachCount == 0) return; _attachCount--; if (_attachCount == 0) { _ticker?.dispose(); _ticker = null; } } void _onTick(Duration elapsed) { _value = _base + elapsed.inMicroseconds / Duration.microsecondsPerSecond; notifyListeners(); } }