import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../ui/theme/app_design_controller.dart'; import '../../ui/theme/app_font_controller.dart'; /// Keeps a detached window's look in step with the main window's. /// /// Both read the design and the font from the device's preferences at /// launch, but each window is its own app instance: a choice made later in /// the main window's Settings reaches this one only when it reads them /// again. It does so on [changes] (the browser's `storage` event, which /// another window of the origin raises as it writes) and whenever the window /// comes back to the front (a desktop process has no such event). class DetachedPreferencesFollower with WidgetsBindingObserver { DetachedPreferencesFollower({ required this._changes, AppDesignController? designs, AppFontController? fonts, Future Function()? reload, }) : _designs = designs ?? AppDesignController.instance, _fonts = fonts ?? AppFontController.instance, _reload = reload ?? _reloadSharedPreferences; final Stream _changes; final AppDesignController _designs; final AppFontController _fonts; final Future Function() _reload; StreamSubscription? _subscription; void start() { WidgetsBinding.instance.addObserver(this); _subscription = _changes.listen((_) => unawaited(follow())); } void dispose() { WidgetsBinding.instance.removeObserver(this); unawaited(_subscription?.cancel()); _subscription = null; } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) unawaited(follow()); } /// Reads the stored design and font again and applies any change. Future follow() async { await _reload(); await Future.wait([_designs.restore(), _fonts.restore()]); } /// The preferences are cached per app instance; another window's writes /// show only after a reload. static Future _reloadSharedPreferences() async { try { await (await SharedPreferences.getInstance()).reload(); } catch (_) { // An unreadable store keeps the look this window has. } } }