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 model
  • NetworkErrorsModel: Network-specific errors
  • ResponseErrorsModel: Response-related errors
  • InternalErrorsModel: 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 verification
  • internetAccessTimeout: Timeout for internet access tests
  • maxRetries: Maximum retry attempts for connectivity checks
  • retryDelay: Delay between retry attempts
  • testUrls: Custom URLs for internet access testing
  • enableConnectionSpeedCheck: Enable connection speed assessment
  • minimumConnectionSpeed: Minimum required connection speed
  • enableLogging: 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 body
  • requestWithoutBody(): Send a request without a body
  • downloadFile<T>(): Download a file
  • uploadFile<FormDataT>(): Upload a file
  • addBaseHeader(): Add a header
  • removeHeader(): Remove a header
  • clearHeader(): Clear all headers
  • addAllInterceptors(): Add multiple interceptors
  • insertInterceptor(): Insert an interceptor at a specific position
  • removeInterceptor(): Remove an interceptor

Method Types

  • MethodTypes.get: GET request
  • MethodTypes.post: POST request
  • MethodTypes.put: PUT request
  • MethodTypes.delete: DELETE request
  • MethodTypes.patch: PATCH request

Response Models

  • BaseNetworkResponseModel<T, E>: Base response model with success/error handling
  • BaseNetworkSuccessModel<T>: Success response model
  • ListResponseModel<T>: List response wrapper

Dependencies

The package relies on the following key dependencies:

  • dio: ^5.8.0+1 - HTTP client for network requests
  • flutter_shared_utilities: ^1.0.4 - Shared utility functions
  • flutter_connectivity_manager: ^1.0.1 - Advanced connectivity management
  • app_logger_manager: ^1.0.0 - Centralized logging system
  • collection: ^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:

  1. Check the documentation
  2. Search existing issues
  3. 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.