dio_network_service 1.0.0
dio_network_service: ^1.0.0 copied to clipboard
A professional, SOLID-compliant network service layer for Flutter, built on top of Dio. Features generic result types, exhaustive error handling with sealed classes, and clean architecture patterns.
Dio Network Service #
A robust, SOLID-compliant network service layer for Flutter, built on top of the powerful Dio package. It simplifies API integrations with generic result types, exhaustive error handling, and a clean architecture.
🚀 Features #
- SOLID Architecture: Built with maintainability and testability in mind.
- Generic Network Results: Uses
NetworkResult<T>to force explicit handling of success and failure states. - Exhaustive Error Handling: Leverages Dart's
sealedclasses forNetworkException, ensuring all error scenarios are accounted for. - Type-Safe Serialization: Built-in support for generic formatters to parse JSON into your domain models.
- Clean API Surface: Decouples transport logic (Dio) from your business services.
- Extensible: Easily add interceptors, loggers, or custom configuration.
📦 Installation #
Add dio_network_service to your pubspec.yaml:
dependencies:
dio_network_service: ^0.0.1
Then run:
flutter pub get
🛠️ Usage #
1. Define Your Model #
Create your model class with a fromJson factory.
class User {
final int id;
final String name;
final String email;
User({required this.id, required this.name, required this.email});
factory User.fromJson(Map<String, dynamic> json) => User(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
2. Create Your API Service #
Extend NetworkService to implement your feature-specific network calls.
import 'package:dio_network_service/dio_network_service.dart';
class UserService extends NetworkService {
UserService(super.client);
Future<NetworkResult<User>> getUser(int id) {
return call((client) => client.get(
'/users/$id',
formatter: (data) => User.fromJson(data),
));
}
Future<NetworkResult<List<User>>> getUsers() {
return call((client) => client.get(
'/users',
formatter: (data) => (data as List)
.map((item) => User.fromJson(item))
.toList(),
));
}
}
3. Initialize and Use #
import 'package:dio/dio.dart';
import 'package:dio_network_service/dio_network_service.dart';
void main() async {
// Setup Dio
final dio = Dio(BaseOptions(
baseUrl: 'https://jsonplaceholder.typicode.com',
connectTimeout: const Duration(seconds: 5),
));
// Initialize Client and Service
final networkClient = DioNetworkClient(dio);
final userService = UserService(networkClient);
// Make Request
final result = await userService.getUser(1);
// Handle Result
result.when(
onSuccess: (user) {
print('User found: ${user.name} (${user.email})');
},
onFailure: (exception) {
print('Network Error: ${exception.message}');
// You can also switch on specific exception types:
// if (exception is UnauthorizedException) { ... }
},
);
}
🛡️ SOLID Principles in Action #
This package is designed to enforce good architectural patterns:
- Dependency Inversion: Your services depend on the
INetworkClientabstraction, allowing you to swap Dio for any other client (or a mock for testing). - Single Responsibility:
NetworkResultmanages state,NetworkExceptionhandles errors, and theNetworkServiceprovides the framework for API calls. - Open/Closed: You can extend functionality through Dio interceptors or custom client implementations without modifying the core package.
📝 License #
This project is licensed under the MIT License - see the LICENSE file for details.