client_network_manager 1.0.1
client_network_manager: ^1.0.1 copied to clipboard
A comprehensive Flutter network manager package with authentication, interceptors, and error handling support.
Flutter Client Network Manager #
A comprehensive Flutter network manager package with authentication, interceptors, and error handling support. This package provides a robust foundation for handling HTTP requests in Flutter applications with built-in support for authentication, caching, file uploads/downloads, and comprehensive error handling.
Features #
- π Easy to use: Simple and intuitive API for making HTTP requests
- π Authentication support: Built-in token management and authentication interceptors
- π‘ Connectivity handling: Automatic connectivity checking and retry mechanisms
- π File operations: Support for file uploads and downloads with progress tracking
- π‘οΈ Error handling: Comprehensive error handling with customizable error models
- π Caching: Built-in response caching with configurable expiration
- π Progress tracking: Real-time progress callbacks for uploads and downloads
- π― Type safety: Full type safety with generic response models
- π Cross-platform: Works on iOS, Android, Web, and Desktop
- π§ Customizable: Highly configurable with custom interceptors and transformers
Installation #
Add this to your package's pubspec.yaml
file:
dependencies:
client_network_manager: ^1.0.0
You can install packages from the command line:
flutter pub get
Quick Start #
Basic Usage #
import 'package:client_network_manager/client_network_manager.dart';
// Create a network manager instance
final networkManager = DefaultBaseNetworkManager(
appLogger, // Your logger instance
connectivityService, // Your connectivity service
baseUrl: 'https://api.example.com',
timeoutSeconds: 30,
);
// Make a GET request
final response = await networkManager.requestWithoutBody(
'/users',
methodType: MethodTypes.get,
);
if (response.isSuccess) {
final users = response.responseData;
print('Users: $users');
} else {
print('Error: ${response.error}');
}
Making POST Requests #
// Create a data model
class UserModel extends BaseDataModel<UserModel> {
final String name;
final String email;
UserModel({required this.name, required this.email});
@override
Map<String, dynamic> toJson() => {
'name': name,
'email': email,
};
@override
UserModel fromJson(Map<String, dynamic> json) => UserModel(
name: json['name'],
email: json['email'],
);
}
// Make a POST request
final user = UserModel(name: 'John Doe', email: 'john@example.com');
final response = await networkManager.sendRequest(
'/users',
body: user,
methodType: MethodTypes.post,
);
if (response.isSuccess) {
print('User created successfully');
} else {
print('Error: ${response.error}');
}
File Upload #
// Upload a file
final formData = FormData.fromMap({
'file': await MultipartFile.fromFile('/path/to/file.jpg'),
'description': 'My file description',
});
final response = await networkManager.uploadFile(
'/upload',
formData,
onSendProgress: (count, total) {
final progress = (count / total * 100).toStringAsFixed(0);
print('Upload progress: $progress%');
},
);
File Download #
// Download a file
final response = await networkManager.downloadFile(
'/files/document.pdf',
onReceiveProgress: (count, total) {
final progress = (count / total * 100).toStringAsFixed(0);
print('Download progress: $progress%');
},
);
if (response.isSuccess) {
final fileBytes = response.responseData.data;
// Save the file
await File('document.pdf').writeAsBytes(fileBytes);
}
Adding Headers #
// Add custom headers
networkManager.addBaseHeader(MapEntry('X-Custom-Header', 'value'));
// Remove a header
networkManager.removeHeader('X-Custom-Header');
// Clear all headers
networkManager.clearHeader();
Configuration #
Network Constants #
// Configure network constants
class NetworkConstants {
static const String baseUrl = 'https://api.example.com';
static const int timeoutSeconds = 30;
static const String contentType = 'application/json';
}
Error Handling #
The package provides comprehensive error handling with different error types:
DefaultErrorModel
: Basic error modelNetworkErrorsModel
: Network-specific errorsResponseErrorsModel
: Response-related errorsInternalErrorsModel
: Internal application errors
// Handle different error types
if (!response.isSuccess) {
switch (response.error.runtimeType) {
case NetworkErrorsModel:
print('Network error: ${response.error}');
break;
case ResponseErrorsModel:
print('Response error: ${response.error}');
break;
case InternalErrorsModel:
print('Internal error: ${response.error}');
break;
default:
print('Unknown error: ${response.error}');
}
}
Advanced Usage #
Custom Interceptors #
// Create a custom interceptor
class CustomInterceptor extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
// Add custom logic before request
print('Making request to: ${options.path}');
handler.next(options);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
// Add custom logic after response
print('Received response: ${response.statusCode}');
handler.next(response);
}
}
// Add the interceptor
networkManager.addAllInterceptors([CustomInterceptor()]);
Authentication #
The package includes built-in authentication support:
// The network manager automatically handles authentication
// when requiresAuth is true (default)
final response = await networkManager.requestWithoutBody(
'/protected-endpoint',
methodType: MethodTypes.get,
requiresAuth: true, // This will include auth headers
);
Caching #
// Enable caching for a request
final response = await networkManager.requestWithoutBody(
'/users',
methodType: MethodTypes.get,
cacheExpiration: Duration(minutes: 5), // Cache for 5 minutes
);
API Reference #
NetworkManager Interface #
The main interface that defines all network operations:
sendRequest<T>()
: Send a request with a bodyrequestWithoutBody()
: Send a request without a bodydownloadFile<T>()
: Download a fileuploadFile<FormDataT>()
: Upload a fileaddBaseHeader()
: Add a headerremoveHeader()
: Remove a headerclearHeader()
: Clear all headersaddAllInterceptors()
: Add multiple interceptorsinsertInterceptor()
: Insert an interceptor at a specific positionremoveInterceptor()
: Remove an interceptor
Method Types #
MethodTypes.get
: GET requestMethodTypes.post
: POST requestMethodTypes.put
: PUT requestMethodTypes.delete
: DELETE requestMethodTypes.patch
: PATCH request
Response Models #
BaseNetworkResponseModel<T, E>
: Base response model with success/error handlingBaseNetworkSuccessModel<T>
: Success response modelListResponseModel<T>
: List response wrapper
Contributing #
Contributions are welcome! Please feel free to submit a Pull Request.
License #
This project is licensed under the MIT License - see the LICENSE file for details.
Support #
If you encounter any issues or have questions, please:
- Check the documentation
- Search existing issues
- Create a new issue
Changelog #
See CHANGELOG.md for a list of changes and version history.