import 'package:flutter/foundation.dart'; /// One server-backed Settings value. /// /// It loads once when its section mounts, never starts a second load while one /// is in flight, and keeps the last good value when a refresh fails, so a /// flaky server shows stale data with a Retry rather than an empty section. class ServerLoad extends ChangeNotifier { ServerLoad(this._fetch); final Future Function() _fetch; T? _value; bool _hasValue = false; Object? _error; bool _loading = false; Future? _inFlight; bool _disposed = false; /// The last value the server returned, or null before the first success. T? get value => _value; bool get hasValue => _hasValue; /// The error from the latest attempt, cleared when a new attempt starts. Object? get error => _error; bool get loading => _loading; /// Starts a load unless one is already running; returns that load's future. Future load() { final running = _inFlight; if (running != null) return running; _loading = true; _error = null; _notify(); final future = _run(); _inFlight = future; return future; } /// Retries after a failure or refreshes a cached value. Future refresh() => load(); Future _run() async { try { final next = await _fetch(); if (_disposed) return; _value = next; _hasValue = true; } catch (error) { if (!_disposed) _error = error; } finally { _loading = false; _inFlight = null; _notify(); } } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; super.dispose(); } }