Networking: http and dio
Two options are common in Flutter:
- `http` — the Dart team's official, minimal package. Enough for simple requests
- `dio` — richer: interceptors, request cancellation, timeout configuration, form data, retry add-ons
The criterion is simple: if you need interceptors (attaching a token to every request, refreshing it on a 401) or cancellation, use dio; if it is a handful of GETs and POSTs, http avoids an extra dependency.
Either way the requests stay behind a repository — widgets never call HTTP directly.
Real networking code involves more than sending a request:
- Timeouts — by default a request can hang for a long time; always set one explicitly
- Status codes — 2xx success, 401 auth, 404 not found, 5xx server; each needs different behaviour
- Token refresh — on a 401, refresh the token and retry; an interceptor is the natural place
- Cancellation — stopping an in-flight request when the user leaves the screen
- Retry — only for idempotent requests; blindly retrying a POST can create a duplicate order
Interview tip. "How do you handle the token?" comes up almost always. A strong answer: I do not attach it by hand on every call — an interceptor does it in one place; on a 401 the interceptor refreshes and retries; and when several 401s arrive in parallel the refresh must happen once (queued), otherwise five refresh requests fire at the same moment. That last detail signals experience.
📚 Sources and documentation
- Networkingofficialdocs.flutter.dev
- http packageofficialpub.dev
- dio packagepub.dev
Interceptors, CancelToken and timeout configuration are documented with examples.