A Flutter Network Layer With Dio

Request packets enter one network-client hub with routes for data, uploads, and a timeout.
Concept illustration of shared network configuration and distinct request policies.

My Flutter apps shared a custom Dio wrapper for configuration, headers, interceptors, and uploads. It reduced repeated setup, but reviewing it also showed where one global policy could accidentally override the needs of an individual request.

The boundary I now aim for is a small configured client, with explicit policies for authentication, response parsing, and retries. A feature should still be able to tell whether it is performing a read, uploading a file, or creating something that must not be repeated.


Share configuration without requiring global state

A shared Dio configuration gives the app consistent timeouts, authentication handling, and environment selection. Dio’s documentation describes instance options, interceptors, cancellation, and multipart requests.

A singleton is one way to distribute that configuration. Passing the configured client into repositories is another, and it makes tests easier to isolate. I care more about consistent ownership than the particular pattern.

This illustrative setup shows a configured client passed into a feature API:

Dio createApiClient(String baseUrl) => Dio(BaseOptions(
  baseUrl: baseUrl,
  connectTimeout: const Duration(seconds: 15),
  receiveTimeout: const Duration(seconds: 30),
  sendTimeout: const Duration(seconds: 30),
));

class OrderApi {
  OrderApi(this.client);
  final Dio client;
}

The example timeout values should be adapted to the operation. Uploads and ordinary reads may warrant different policies. Environment selection should also be intentional; changing a global base URL while requests are in flight can make failures hard to reproduce.


Let interceptors handle cross-cutting concerns

Authentication headers, safe request diagnostics, and standard transport error mapping fit naturally into interceptors. Credentials should only be attached to the intended API origin, including when a client follows redirects or is reused for another host. Business decisions generally belong closer to the feature.

For example, a response envelope may contain an application code, but that convention should be parsed only for endpoints that use it. A successful file download or a 204 No Content response should not fail because it lacks data['code'] == 200.

The wrapper should preserve useful evidence: HTTP status, application error code, operation, and an appropriate correlation ID. Turning every failure into a string discards information the UI and tests may need.


Define retry policy for each operation

A read that fails before receiving a response can often be retried. A request to create an order or transfer money is different. The server may have applied it even if the client timed out.

For those operations, I would use server-supported idempotency and a way to query the resulting state. Repeating the HTTP call without that agreement risks repeating the action.

Authentication refresh has its own concurrency concern. Several requests can fail authorization together, and independent refresh attempts can race. A coordinated in-flight refresh is a useful pattern, with a strict retry limit and an escape from the interceptor loop.


Treat uploads as a distinct operation

Multipart uploads need the correct content type and boundary. Dio can build them from FormData; forcing a URL-encoded content type over that request is the wrong default.

// Illustrative upload; server-side validation is still required.
final form = FormData.fromMap({
  'file': await MultipartFile.fromFile(file.path, filename: fileName),
});
await client.post('/uploads', data: form, cancelToken: cancelToken);

Progress, cancellation, size limits, and validation are also part of the experience. For a retry, create fresh FormData and MultipartFile objects; Dio documents this requirement because an earlier request can finalize their streams.


Log what helps, omit what harms

The method, route pattern, status, and duration are often sufficient to begin investigation. Tokens, passwords, raw payment data, and full private response bodies are poor logging defaults. Debug mode alone does not make realistic user data safe to print.

The UI should receive a meaningful error category, such as offline, timeout, unauthorized, validation failure, or conflict. Raw exception text rarely gives the user a useful next step.


Test the policy at the boundary

I would verify header injection, cancellation, known response shapes, empty success responses, malformed data, concurrent refresh, and retry behavior. A fake transport can cover these cases without contacting a live backend.

I would keep the wrapper small enough that its behavior can be read and tested. Its value is consistent defaults, useful failure evidence, and a deliberate escape for requests that need a different policy.