Connecting Flutter to a Backend with Dio: Models, Errors and Clean Structure
Every real app talks to an API. This guide shows how to make requests with Dio, turn responses into Dart models, handle errors properly and keep network code in a clean layer.
3 min read1 views
Almost every real app talks to a server. Flutter can use the http package, but Dio adds interceptors, request cancellation and upload progress, and is more common in serious projects.
Convert the JSON response into a Dart class so the rest of your code works with typed objects, not raw Maps:
class Course {
final String id;
final String name;
final int price;
const Course({required this.id, required this.name, required this.price});
factory Course.fromJson(Map<String, dynamic> json) => Course(
id: json['id'] as String,
name: json['name'] as String,
price: json['price'] as int,
);
}
Widgets should not call Dio directly. Create an intermediary class:
class CourseRepository {
CourseRepository(this._dio);
final Dio _dio;
Future<List<Course>> fetchCourses() async {
final response = await _dio.get('/courses');
return (response.data as List)
.map((e) => Course.fromJson(e as Map<String, dynamic>))
.toList();
}
}
If the API address or format changes one day, only this class changes.
Network errors come in several kinds: no connection, a timeout, an error response from the server. Turn them all into one understandable message:
String friendlyMessage(Object error) {
if (error is DioException) {
switch (error.type) {
case DioExceptionType.connectionTimeout:
case DioExceptionType.receiveTimeout:
return 'The server did not respond. Please try again.';
case DioExceptionType.connectionError:
return 'Check your internet connection.';
default:
final data = error.response?.data;
if (data is Map && data['message'] is String) return data['message'];
}
}
return 'Something went wrong.';
}
As an app grows, code falls apart without structure. This article explains feature-first folders, UI, state, repository and data-source layers and the principles of testability in plain language.
Becoming a full-stack developer with Flutter and FastAPI is entirely doable. This article shows the road map from the first endpoint and Pydantic models to PostgreSQL, migrations and Docker deployment.
A step-by-step guide from installing the Flutter SDK to running your first app and understanding the project structure, with tips that save you time at the start.