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, comprehensive connectivity management, and advanced error handling.
Features
- π Easy to use: Simple and intuitive API for making HTTP requests
- π Authentication support: Built-in token management and authentication interceptors
- π‘ Advanced connectivity handling: Multi-level connectivity checking with 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
- π Enhanced logging: Integrated logging system with structured data
- β‘ Connection optimization: Intelligent connection speed assessment and optimization
Installation
Add this to your package's pubspec.yaml
file:
dependencies:
client_network_manager: ^x.y.z
flutter_connectivity_manager: ^x.y.z
app_logger_manager: ^x.y.z
You can install packages from the command line:
flutter pub get
Quick Start
Basic Usage
import 'package:client_network_manager/client_network_manager.dart';
import 'package:app_logger_manager/app_logger_manager.dart';
import 'package:flutter_connectivity_manager/flutter_connectivity_manager.dart';
// Initialize required dependencies
final appLogger = AppLoggerManager();
final connectivityManager = ConnectivityManager();
// Create a network manager instance
final networkManager = DefaultBaseNetworkManager(
appLogger,
connectivityManager,
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}');
}
Enhanced Connectivity Configuration
// Configure connectivity checking
final connectivityConfig = ConnectivityCheckConfig(
enableInternetAccessTest: true,
internetAccessTimeout: Duration(seconds: 5),
maxRetries: 3,
retryDelay: Duration(milliseconds: 500),
enableConnectionSpeedCheck: true,
minimumConnectionSpeed: ConnectionSpeed.good,
enableLogging: true,
testUrls: [
'https://www.google.cn',
'https://www.cloudflare.com',
],
);
// The connectivity interceptor will automatically use this configuration
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 Features
Enhanced Connectivity Management
The package now includes advanced connectivity management with multiple validation layers:
// Connectivity checking includes:
// - Basic network connectivity
// - Internet access verification
// - Connection speed assessment
// - Retry mechanisms with exponential backoff
// - Custom test URLs for reliability
final connectivityConfig = ConnectivityCheckConfig(
enableInternetAccessTest: true,
enableConnectionSpeedCheck: true,
minimumConnectionSpeed: ConnectionSpeed.good,
maxRetries: 3,
retryDelay: Duration(seconds: 1),
testUrls: ['https://www.google.cn', 'https://8.8.8.8'],
);
Integrated Logging System
// Enhanced logging with structured data
final appLogger = AppLoggerManager(
logLevel: LogLevel.debug,
enableFileLogging: true,
enableConsoleLogging: true,
);
// The network manager automatically logs:
// - Request/response details
// - Connectivity status
// - Authentication events
// - Error information with context
Authentication with Enhanced Error Handling
// The authentication system now includes:
// - Improved token refresh logic
// - Better error recovery mechanisms
// - Support for more HTTP error codes
// - Enhanced session management
final response = await networkManager.requestWithoutBody(
'/protected-endpoint',
methodType: MethodTypes.get,
requiresAuth: true, // Automatic token handling with retry logic
);
API Reference
ConnectivityCheckConfig
Configure comprehensive connectivity checking:
enableInternetAccessTest
: Perform internet access verificationinternetAccessTimeout
: Timeout for internet access testsmaxRetries
: Maximum retry attempts for connectivity checksretryDelay
: Delay between retry attemptstestUrls
: Custom URLs for internet access testingenableConnectionSpeedCheck
: Enable connection speed assessmentminimumConnectionSpeed
: Minimum required connection speedenableLogging
: Enable detailed connectivity logging
Enhanced NetworkManager Interface
The main interface now includes enhanced features:
- Enhanced connectivity management with
ConnectivityCheckConfig
- Integrated logging with
AppLogger
- Improved error handling with intelligent retry mechanisms
- Better authentication flow with token refresh capabilities
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
Dependencies
The package relies on the following key dependencies:
dio: ^5.8.0+1
- HTTP client for network requestsflutter_shared_utilities: ^1.0.4
- Shared utility functionsflutter_connectivity_manager: ^1.0.1
- Advanced connectivity managementapp_logger_manager: ^1.0.0
- Centralized logging systemcollection: ^1.19.1
- Enhanced collection operations
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.
Libraries
- client_network_manager
- A collection of network-related utilities and classes for managing network requests, responses, and configurations in a Dart application.