Network State Management in Flutter: Loading, Offline, and Retry
Architecture for network-aware Flutter state: a sealed request state, connectivity vs real reachability, backoff with idempotency, offline queues, and tests.
Published on • November 12, 2026
AI Assistant

Most “networking bugs” are really state-model bugs: a spinner that never clears, a cached list that hides fresh data, or a retry storm that turns one timeout into fifty requests. The fix is architectural, not a package. Model the request lifecycle explicitly, treat connectivity as a hint, and put retry, idempotency, and queuing behind one testable layer.
Connectivity is not reachability
connectivity_plus (7.3.2, Flutter Favorite) reports transports: checkConnectivity() returns a List<ConnectivityResult> and onConnectivityChanged streams it. Its own readme warns you not to decide request success from it, because a hotel captive portal reports wifi with no internet. The existing connectivity monitoring post shows the HTTP probe pattern; in state terms, connectivity is an input to your state machine, never the state itself:
Future<void> _onConnectivityChanged(List<ConnectivityResult> results) async {
final online = results.hasConnectivity && await _probe();
_emit(online ? const NetState.online() : const NetState.offline());
}
Probe only on transitions, not on every frame, and keep a cooldown so a flapping NWPathMonitor cannot spam your backend.
Modeling the request lifecycle as a sealed type
A sealed class makes every state reachable and every transition exhaustive:
sealed class NetState<T> {
const NetState();
}
final class Idle<T> extends NetState<T> { const Idle(); }
final class Loading<T> extends NetState<T> { const Loading(); }
final class Data<T> extends NetState<T> {
const Data(this.value, {this.stale = false});
final T value;
final bool stale;
}
final class Failure<T> extends NetState<T> {
const Failure(this.error, this.stack);
final Object error;
final StackTrace stack;
}
final class Offline<T> extends NetState<T> { const Offline(); }
The stale flag on Data is the detail people miss: when connectivity drops, showing last-known data with a stale marker beats blanking the screen. Because the class is sealed, a switch in the UI must handle every case, so a new state cannot silently fall through.
Retry with exponential backoff and idempotency
The retry package (3.1.2) gives you exponential backoff out of the box: 8 attempts by default, sleeping 400 ms, 800 ms, 1600 ms and so on, each jittered by ±25%:
final r = RetryOptions(maxAttempts: 5, delayFactor: const Duration(seconds: 1));
final user = await r.retry(
() => _api.fetchUser(id),
retryIf: (e) =>
e is DioException &&
(e.type == DioExceptionType.connectionTimeout ||
e.type == DioExceptionType.receiveTimeout ||
(e.response?.statusCode ?? 500) >= 500),
);
Two rules keep this safe. Only retry idempotent operations (GET, PUT, DELETE, or POST with an idempotency key in the header); never blind-retry a payment POST. And classify first: 4xx other than 429 means stop, 5xx and timeouts mean retry, 401 means refresh the token through a QueuedInterceptor as the dio and Retrofit networking post explains.
Offline request queues
When the probe fails, do not drop the user’s action. Persist the mutation, flush on reconnect:
Future<void> submit(ProfilePatch patch) async {
if (await _probe()) {
try { await _api.save(patch); return; }
on DioException catch (e) { if (!_isTransient(e)) rethrow; }
}
await _queue.enqueue(patch); // durable, ordered, idempotent
}
Flush in order, give each entry a client-generated id so the server can deduplicate, and cap the queue size so a long offline stretch does not exhaust storage. If a queued entry fails permanently, surface it as a Failure for that item instead of blocking the whole queue.
When to invalidate cached UI
Invalidate on evidence, not on hope. Clear or mark data stale when a mutation succeeds, when the server says the content changed (ETag or version mismatch), or when the app resumes after a long background period. Do not invalidate on every connectivity blip: a false none followed by wifi would refetch a list the user is already reading. Prefer “serve cache, refresh in background, swap on arrival” over “show spinner, then data.”
Testable patterns
Keep the state machine pure: it takes events (connectivity, probe result, repository result) and emits states, with no widget or plugin imports. In tests, inject a fake prober and a fake repository:
test('drops to offline when the probe fails', () async {
final store = RequestCubit(repo: FakeRepo(), prober: OfflineProber());
await store.refresh();
expect(store.state, isA<Offline<void>>());
});
Widget tests then only assert rendering per state, which is fast and deterministic.
Common pitfalls
- Treating
onConnectivityChangedas truth; iOSNWPathMonitorcan emitnoneimmediately beforewifi. - Retrying non-idempotent writes, or retrying without jitter, which synchronizes clients into a thundering herd.
- Holding a
CancelTokenpast widget disposal and swallowing the resultingDioExceptionas if it were a real failure. - Forgetting
connectTimeout/receiveTimeout, soLoadingnever resolves on a dead network. - Emitting states from the repository layer, which makes transitions impossible to test.
Takeaway: Represent idle, loading, data (with a stale flag), failure, and offline as one sealed type, treat connectivity plus a reachability probe as inputs to that machine, retry only classified transient errors on idempotent calls with jittered backoff, queue mutations durably while offline, and keep the machine pure so tests need no plugins.