Every Flutter app talks to a server, and the networking code is where small inconsistencies multiply: one screen handles timeouts, another crashes, a third shows a raw exception message. A good network layer centralizes those decisions so feature code stays boring.
This is the structure I use with Dio and Retrofit.
Layout
core/network/
dio_factory.dart # base options + interceptors
interceptors/
auth_interceptor.dart
logging_interceptor.dart
failure.dart # typed errors
result.dart # Ok / Err
features/orders/data/
order_api.dart # Retrofit interface
order_repository_impl.dart
One configured Dio
Dio createDio({required String baseUrl, bool debug = false}) {
final dio = Dio(BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 20),
headers: {'Accept': 'application/json'},
));
dio.interceptors.add(AuthInterceptor(/* ... */));
if (debug) {
dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
}
return dio;
}
Never enable body logging in release builds: it prints tokens and personal data into device logs.
A typed API with Retrofit
Retrofit generates the boilerplate from an annotated interface:
part 'order_api.g.dart';
@RestApi()
abstract class OrderApi {
factory OrderApi(Dio dio) = _OrderApi;
@GET('/orders')
Future<List<OrderDto>> fetchOrders(@Query('page') int page);
@POST('/orders')
Future<OrderDto> createOrder(@Body() CreateOrderRequest body);
}
Compile-time checked paths and parameters replace string concatenation scattered across the app. Combine it with freezed or json_serializable for the DTOs.
Map errors once
Do not let DioException escape the data layer. Convert it into a small set of failures the UI can reason about:
sealed class Failure {
const Failure(this.message);
final String message;
factory Failure.fromDio(DioException e) => switch (e.type) {
DioExceptionType.connectionTimeout ||
DioExceptionType.receiveTimeout ||
DioExceptionType.sendTimeout => const TimeoutFailure(),
DioExceptionType.connectionError => const OfflineFailure(),
DioExceptionType.badResponse => switch (e.response?.statusCode) {
401 => const UnauthorizedFailure(),
422 => ValidationFailure(e.response?.data),
final c? when c >= 500 => const ServerFailure(),
_ => const UnknownFailure(),
},
_ => const UnknownFailure(),
};
}
final class TimeoutFailure extends Failure { const TimeoutFailure() : super('The request timed out.'); }
final class OfflineFailure extends Failure { const OfflineFailure() : super('No internet connection.'); }
// ... Unauthorized, Validation, Server, Unknown
Because Failure is sealed, a switch in your BLoC must handle every case, and the compiler tells you when a new one appears.
Return a result, not exceptions
sealed class Result<T> { const Result(); }
final class Ok<T> extends Result<T> { const Ok(this.value); final T value; }
final class Err<T> extends Result<T> { const Err(this.failure); final Failure failure; }
The repository returns Result<List<Order>>. Callers cannot forget the error path, which is the most common source of "works on my machine" bugs.
Retrying safely
Retry is useful but dangerous:
- Retry idempotent requests (
GET,PUT,DELETE) on timeouts and5xx, with exponential backoff and jitter. - Do not blindly retry
POSTunless the server supports an idempotency key; you can create duplicate orders. See the idempotency discussion in offline-first Flutter apps. - Never retry
4xx(other than401handled by auth, see JWT refresh in Flutter).
Testing the layer
Put Dio behind an adapter you control (http_mock_adapter, or a fake HttpClientAdapter) and assert the mapping: a 503 becomes ServerFailure, a timeout becomes TimeoutFailure. Since the repository is an interface, feature tests never touch Dio at all; see testing Flutter apps.
Key takeaways
- One configured Dio, interceptors for cross-cutting concerns.
- Retrofit for typed, generated API clients.
- Map exceptions to a sealed
Failureat the data boundary and returnResult. - Retry only what is safe to retry.
On a previous project, rebuilding the network layer this way made new endpoints much faster to add and error handling consistent across screens. Hiring for mobile? Contact me.