A Flutter package for simplified API communication using Dio HTTP client.
- Easy API request configuration
- Built-in environment management
- Support for various HTTP methods
- File upload capabilities
- Progress tracking
- Structured error handling
Add this to your package's pubspec.yaml file:
dependencies:
gtd_network: ^1.0.5- Create an environment for your API:
final environment =BaseEnvironment(
baseUrl:'api.example.com', // Base URL without protocol
platformPath:'api/v1', // Path prefix for all endpoints
headers: { // Default headers'Accept':'application/json',
'Content-Type':'application/json',
},
);- Create an endpoint for your request:
final endpoint =GtdEndpoint(
env: environment,
path:'users', // This will be appended to the platformPath
);- Configure a network request:
final networkService =GtdNetworkService.shared;
networkService.request =GTDNetworkRequest(
type:GtdMethod.get, // HTTP method
enpoint: endpoint,
queryParams: { // Optional query parameters'page':1,
'limit':10,
},
data: { // Optional request body for POST/PUT'name':'John Doe',
'email':'john@example.com',
},
);- Execute the request:
try {
final response =await networkService.execute();
print('Status code: ${response.statusCode}');
print('Response data: ${response.data}');
} onDioExceptioncatch (e) {
print('Request failed: ${e.message}');
}// Create environment and endpointfinal environment =BaseEnvironment(
baseUrl:'jsonplaceholder.typicode.com',
platformPath:'',
headers: {'Accept':'application/json'},
);
final endpoint =GtdEndpoint(env: environment, path:'posts');
// Configure requestfinal networkService =GtdNetworkService.shared;
networkService.request =GTDNetworkRequest(
type:GtdMethod.get,
enpoint: endpoint,
queryParams: {'userId':1},
);
// Executetry {
final response =await networkService.execute();
print('GET request successful: ${response.statusCode}');
print('Data: ${response.data}');
} catch (e) {
final gtdError = e asGtdError;
print('GET request failed: ${gtdError.message}');
}// Create environment and endpointfinal environment =BaseEnvironment(
baseUrl:'jsonplaceholder.typicode.com',
platformPath:'',
headers: {'Accept':'application/json'},
);
// Getting a specific post by IDfinal postId =1;
final endpoint =GtdEndpoint(env: environment, path:'posts/$postId');
// Configure requestfinal networkService =GtdNetworkService.shared;
networkService.request =GTDNetworkRequest(
type:GtdMethod.get,
enpoint: endpoint,
);
// Executetry {
final response =await networkService.execute();
print('GET request successful: ${response.statusCode}');
print('Post data: ${response.data}');
// Access specific fieldsprint('Title: ${response.data['title']}');
print('Body: ${response.data['body']}');
} catch (e) {
final gtdError = e asGtdError;
print('GET request failed: ${gtdError.message}');
}// Create a file to uploadfinal file =File('path/to/your/file.jpg');
// Configure environment and endpointfinal environment =BaseEnvironment(
baseUrl:'api.example.com',
platformPath:'api/v1',
headers: {'Accept':'application/json'},
);
final endpoint =GtdEndpoint(env: environment, path:'upload');
// Configure requestfinal networkService =GtdNetworkService.shared;
networkService.request =GTDNetworkRequest(
type:GtdMethod.post,
enpoint: endpoint,
data: {'description':'Profile picture'},
);
// Upload filetry {
final response =await networkService.uploadFile(
file: file,
fieldName:'image',
onSendProgress: (int sent, int total) {
final progress = (sent / total *100).toStringAsFixed(2);
print('Upload progress: $progress%');
},
);
print('Upload successful: ${response.statusCode}');
print('Response: ${response.data}');
} catch (e) {
final gtdError = e asGtdError;
print('Upload failed: ${gtdError.message}');
}// Add authentication token to all requests
environment.headers['Authorization'] ='Bearer YOUR_TOKEN_HERE';// Customize timeout settings
networkService.connectTimeout =constDuration(seconds:10);
networkService.receiveTimeout =constDuration(seconds:30);final testEnvironment =BaseEnvironment(
baseUrl:'localhost:8080', // Point to your mock server
platformPath:'mock/api',
headers: {'Accept':'application/json'},
);The package provides a standardized way to handle errors with the GtdError class. All network service methods will only throw GtdError exceptions, making error handling consistent across the application:
try {
final response =await networkService.execute();
return response.data;
} catch (e) {
// All exceptions from networkService are GtdErrorfinal gtdError = e asGtdError;
// You can access additional propertiesprint('Status code: ${gtdError.statusCode}');
print('Error message: ${gtdError.message}');
print('Stack trace: ${gtdError.stackTrace}');
// You can check for specific errorsif (gtdError.statusCode ==401) {
// Handle authentication errors
} elseif (gtdError.errorCode =='NETWORK_ERROR') {
// Handle network connectivity issues
}
// Rethrow or handle the errorthrow gtdError;
}The GtdError class provides these properties:
message: Human-readable error messagestatusCode: HTTP status code if availableerrorCode: Custom error code for categorizationoriginalError: Original error that caused this exception, which can be another GtdErrorstackTrace: Full stack trace for debugging
// Create from DioException (used internally)final error1 =GtdError.fromDioError(dioException);
// Create from any exceptionfinal error2 =GtdError.fromException(exception, stackTrace);
// Create with custom messagefinal error3 =GtdError.custom(
'Custom error message',
statusCode:400,
errorCode:'VALIDATION_FAILED',
);
// Create from another GtdErrorfinal error4 =GtdError.fromError(
existingError,
message:'More specific error message',
errorCode:'SPECIFIC_ERROR_CODE',
);You can use the getOriginalErrorSource() method to get the root cause of errors:
final rootCause = gtdError.getOriginalErrorSource();
print('Root cause: $rootCause');For debugging, you can get a detailed error report:
final error =GtdError.fromDioError(dioException);
print(error.toDetailedString());This will output:
GtdError: Resource not found (404) [code: 404]
Original error: DioException [...]
Stack trace:
#0 ...
You can organize your API calls into dedicated resource modules following this structure:
user_resource/
├── api/
│ └── user_resource_api.dart
├── models/
│ ├── request/
│ │ └── gtd_user_profile_rq.dart
│ └── response/
│ ├── gtd_user_detail_rs.dart
│ └── gtd_user_list_rs.dart
├── gtd_user_endpoint.dart
└── user_resource.dart
- Create endpoints in a dedicated class:
// gtd_user_endpoint.dartclassGtdUserEndpointextendsGtdEndpoint {
GtdUserEndpoint({requiredsuper.env, requiredsuper.path});
// Define API paths as constantsstaticconstString kGetUserDetail ='/api/users/profile';
staticconstString kGetUserList ='/api/users/list';
// Create factory methods for each endpointstaticGtdEndpointgetUserDetail(GTDEnvType envType, String userId) {
const path = kGetUserDetail;
returnGtdEndpoint(env:GtdEnvironment(env: envType), path:"$path/$userId");
}
staticGtdEndpointgetUserList(GTDEnvType envType) {
const path = kGetUserList;
returnGtdEndpoint(env:GtdEnvironment(env: envType), path: path);
}
}- Create request/response models:
// models/request/gtd_user_profile_rq.dartclassGtdUserProfileRq {
String userId;
bool includeSettings;
bool includePreferences;
// Constructor, toMap(), fromMap(), etc.Map<String, dynamic> toMap() {
return<String, dynamic>{
'userId': userId,
'includeSettings': includeSettings,
// Other properties...
};
}
}- Implement the API client:
// api/user_resource_api.dartclassUserResourceApi {
GtdNetworkService networkService =GtdNetworkService.shared;
GTDEnvType envType =AppConst.shared.envType;
UserResourceApi._();
staticfinal shared =UserResourceApi._();
Future<GtdUserDetail> getUserDetailById(String userId) async {
try {
final networkRequest =GTDNetworkRequest(
type:GtdMethod.get, enpoint:GtdUserEndpoint.getUserDetail(envType, userId)
);
networkService.request = networkRequest;
final response =await networkService.execute();
GtdUserDetailRs userDetailRs =JsonParser.jsonToModel(
GtdUserDetailRs.fromJson, response.data
);
if ((userDetailRs.errors ?? []).isNotEmpty) {
throwGtdApiError.fromErrorConstant(GtdErrorConstant.unknown);
}
return userDetailRs.result ??GtdUserDetail();
} catch (e) {
// All errors from networkService are GtdErrorthrow e;
}
}
// Other API methods...
}- Create an export file:
// user_resource.dartexport'api/user_resource_api.dart';
export'gtd_user_endpoint.dart';
export'models/response/gtd_user_detail_rs.dart';// Import the resource moduleimport'package:your_package/network/user_resource/user_resource.dart';
// Usage in your applicationFuture<void> fetchUserDetails() async {
try {
// Use the API clientfinal userApi =UserResourceApi.shared;
final userId ="user123";
// Call the API methodfinal userDetail =await userApi.getUserDetailById(userId);
// Process the resultsprint('User name: ${userDetail.fullName}');
print('Email: ${userDetail.email}');
// Process other properties...
} catch (e) {
print('Error fetching user details: $e');
}
}
// Example with request modelFuture<void> searchUsers() async {
try {
// Create the request modelfinal request =GtdUserSearchRq(
searchTerm:"john",
pageSize:20,
pageNumber:1,
includeSuspended:false,
);
// Call the API with the request modelfinal userApi =UserResourceApi.shared;
final users =await userApi.searchUsers(request);
// Process the resultsprint('Found ${users.length} users');
for (var user in users) {
print('User: ${user.fullName} - ${user.email}');
}
} catch (e) {
print('Error searching users: $e');
}
}For a complete working example including both GET requests and file uploads, see the examples in the test directory:
test/api_test_example.dart- Main example class with implementationtest/run_api_test.dart- Runner for the API exampletest/run_api_test_simple.dart- Simple direct implementation using Dio
This project is licensed under the MIT License.