|
1 | | -# http_client |
| 1 | +<div align="center"> |
| 2 | + <img src="https://avatars.githubusercontent.com/u/202675624?s=400&u=dc72a2b53e8158956a3b672f8e52e39394b6b610&v=4" alt="Flutter News App Toolkit Logo" width="220"> |
| 3 | + <h1>HTTP Client</h1> |
| 4 | + <p><strong>A robust and reusable Dart HTTP client built on top of the `dio` package, serving as a crucial abstraction layer within the Flutter News App Full Source Code Toolkit.</strong></p> |
| 5 | +</div> |
2 | 6 |
|
3 | | - |
4 | | -[](https://pub.dev/packages/very_good_analysis) |
5 | | -[](https://polyformproject.org/licenses/free-trial/1.0.0) |
| 7 | +<p align="center"> |
| 8 | + <img src="https://img.shields.io/badge/coverage-68%25-green?style=for-the-badge" alt="coverage: XX%"> |
| 9 | + <a href="https://flutter-news-app-full-source-code.github.io/docs/"><img src="https://img.shields.io/badge/LIVE_DOCS-VIEW-slategray?style=for-the-badge" alt="Live Docs: View"></a> |
| 10 | + <a href="https://github.com/flutter-news-app-full-source-code"><img src="https://img.shields.io/badge/MAIN_PROJECT-BROWSE-purple?style=for-the-badge" alt="Main Project: Browse"></a> |
| 11 | +</p> |
6 | 12 |
|
7 | | -A robust and reusable Dart HTTP client built on top of the `dio` package. It simplifies API interactions by providing common HTTP methods, automatic authentication header injection, and mapping network/status code errors to specific custom exceptions. |
| 13 | +This `http_client` package serves as the foundational HTTP client for the [**Flutter News App Full Source Code Toolkit**](https://github.com/flutter-news-app-full-source-code). Built on top of the `dio` package, it simplifies API interactions by providing common HTTP methods, automatic authentication header injection, and mapping network/status code errors to specific custom exceptions. It ensures consistent and robust communication with backend services across the Flutter mobile app, web dashboard, and Dart Frog backend API. |
8 | 14 |
|
9 | | -## Description |
| 15 | +## ⭐ Feature Showcase: Streamlined & Secure API Communication |
10 | 16 |
|
11 | | -This package provides an `HttpClient` class designed to be used as a foundational data access component in Dart or Flutter applications. It abstracts away the complexities of setting up `dio`, handling authentication tokens, and interpreting various HTTP error conditions, offering a cleaner interface for making API calls. |
| 17 | +This package provides a comprehensive set of features for managing HTTP requests. |
12 | 18 |
|
13 | | -Key features include: |
14 | | -* Base URL configuration. |
15 | | -* Simplified `get`, `post`, `put`, `delete` methods. |
16 | | -* Automatic injection of `Authorization: Bearer <token>` headers via an interceptor. |
17 | | -* Token retrieval via a flexible `TokenProvider` function. |
18 | | -* Mapping of `DioException` types and non-2xx HTTP status codes to specific `HttpException` subtypes (`NetworkException`, `BadRequestException`, `UnauthorizedException`, etc.) defined in the `core` package. |
19 | | -* Support for request cancellation using `dio`'s `CancelToken`. |
| 19 | +<details> |
| 20 | +<summary><strong>🧱 Core Functionality</strong></summary> |
20 | 21 |
|
21 | | -## Getting Started |
| 22 | +### 🚀 Robust `HttpClient` |
| 23 | +- **`HttpClient` Class:** The main entry point for making HTTP requests, abstracting away `dio` complexities. |
| 24 | +- **Simplified HTTP Methods:** Provides `get<T>()`, `post<T>()`, `put<T>()`, and `delete<T>()` methods for common API interactions. |
22 | 25 |
|
23 | | -Add the package to your `pubspec.yaml`: |
| 26 | +### 🔐 Automatic Authentication |
| 27 | +- **`AuthInterceptor`:** Automatically injects `Authorization: Bearer <token>` headers into requests. |
| 28 | +- **Flexible `TokenProvider`:** Retrieves authentication tokens via a configurable asynchronous function, allowing integration with various authentication mechanisms. |
24 | 29 |
|
25 | | -```yaml |
26 | | -dependencies: |
27 | | - http_client: |
28 | | - git: |
29 | | - url: https://github.com/flutter-news-app-full-source-code/http-client.git |
30 | | - dio: ^5.8.0+1 # http_client relies on dio |
31 | | -``` |
| 30 | +### 🛡️ Standardized Error Handling |
| 31 | +- **`ErrorInterceptor`:** Maps `DioException` types and non-2xx HTTP status codes to specific `HttpException` subtypes (e.g., `NetworkException`, `BadRequestException`, `UnauthorizedException`, `NotFoundException`, `ServerException`, `UnknownException`) defined in the `core` package. This ensures predictable and consistent error management across the application layers. |
32 | 32 |
|
33 | | -Then run `dart pub get` or `flutter pub get`. |
| 33 | +### ⚡ Performance & Control |
| 34 | +- **Request Cancellation:** Supports request cancellation using `dio`'s `CancelToken` for improved resource management and user experience. |
| 35 | +- **Configurable Timeouts:** Allows configuration of connection, receive, and send timeouts for robust network operations. |
34 | 36 |
|
35 | | -## Features |
| 37 | +### 🌐 Platform Adaptability |
| 38 | +- **`BrowserHttpClientAdapter` & `IOHttpClientAdapter`:** Automatically selects the appropriate HTTP client adapter for web and non-web platforms, ensuring seamless operation across different environments. |
36 | 39 |
|
37 | | -* **`HttpClient` Class:** The main entry point for making requests. |
38 | | -* **HTTP Methods:** `get<T>()`, `post<T>()`, `put<T>()`, `delete<T>()`. |
39 | | -* **Authentication:** Automatic Bearer token injection using a provided `TokenProvider`. |
40 | | -* **Error Handling:** Throws specific `HttpException` subtypes (defined in `core`) for easier error management. |
41 | | -* **Cancellation:** Supports request cancellation via `CancelToken`. |
| 40 | +> **💡 Your Advantage:** You get a meticulously designed, production-quality HTTP client that simplifies API interactions, ensures secure authentication, provides robust error handling, and adapts to different platforms. This package accelerates development by providing a solid foundation for network communication. |
42 | 41 |
|
43 | | -## Usage |
44 | | - |
45 | | -```dart |
46 | | -import 'package:http_client/http_client.dart'; |
47 | | -import 'package:core/core.dart'; // Import for HttpException types |
48 | | -import 'package:dio/dio.dart'; // For CancelToken |
49 | | -
|
50 | | -// 1. Define your token provider function |
51 | | -// (This would typically fetch the token from secure storage, auth state, etc.) |
52 | | -Future<String?> myTokenProvider() async { |
53 | | - // Replace with your actual token retrieval logic |
54 | | - await Future.delayed(const Duration(milliseconds: 50)); // Simulate async fetch |
55 | | - return 'your_super_secret_auth_token'; |
56 | | -} |
57 | | -
|
58 | | -void main() async { |
59 | | - // 2. Create an instance of the client |
60 | | - final client = HttpClient( |
61 | | - baseUrl: 'https://api.example.com/v1', |
62 | | - tokenProvider: myTokenProvider, |
63 | | - ); |
64 | | -
|
65 | | - // 3. Make requests |
66 | | -
|
67 | | - // Example GET request |
68 | | - try { |
69 | | - final headlines = await client.get<List<dynamic>>('/headlines'); |
70 | | - print('Fetched headlines: $headlines'); |
71 | | -
|
72 | | - // Example GET with query parameters and cancellation |
73 | | - final cancelToken = CancelToken(); |
74 | | - Future.delayed(const Duration(milliseconds: 100), () { |
75 | | - print('Cancelling search request...'); |
76 | | - cancelToken.cancel('User navigated away'); |
77 | | - }); |
78 | | -
|
79 | | - final searchResults = await client.get<Map<String, dynamic>>( |
80 | | - '/search', |
81 | | - queryParameters: {'q': 'flutter', 'limit': 10}, |
82 | | - cancelToken: cancelToken, // Pass the token here |
83 | | - ); |
84 | | - print('Search results: $searchResults'); |
85 | | -
|
86 | | - } on UnauthorizedException catch (e) { |
87 | | - print('Authentication error: ${e.message}'); |
88 | | - // Handle token refresh or prompt user to login |
89 | | - } on NetworkException catch (e) { |
90 | | - print('Network error: ${e.message}'); |
91 | | - // Handle offline state or retry logic |
92 | | - } on NotFoundException catch (e) { |
93 | | - print('Resource not found: ${e.message}'); |
94 | | - } on HttpException catch (e) { // Catch other specific or general client errors |
95 | | - print('HTTP Client Error: ${e.message}'); |
96 | | - } catch (e) { // Catch any other unexpected errors |
97 | | - print('An unexpected error occurred: $e'); |
98 | | - } |
99 | | -
|
100 | | - // Example POST request |
101 | | - try { |
102 | | - final newItem = await client.post<Map<String, dynamic>>( |
103 | | - '/items', |
104 | | - data: {'name': 'New Item', 'value': 123}, |
105 | | - ); |
106 | | - print('Created item: $newItem'); |
107 | | - } on HttpException catch (e) { |
108 | | - print('Error creating item: ${e.message}'); |
109 | | - } |
110 | | -} |
111 | | -
|
112 | | -``` |
| 42 | +</details> |
113 | 43 |
|
114 | 44 | ## 🔑 Licensing |
115 | 45 |
|
116 | | -This package is source-available and licensed under the [PolyForm Free Trial 1.0.0](LICENSE). Please review the terms before use. |
117 | | - |
118 | | -For commercial licensing options that grant the right to build and distribute unlimited applications, please visit the main [**Flutter News App - Full Source Code Toolkit**](https://github.com/flutter-news-app-full-source-code) organization. |
| 46 | +This `http_client` package is an integral part of the [**Flutter News App Full Source Code Toolkit**](https://github.com/flutter-news-app-full-source-code). For comprehensive details regarding licensing, including trial and commercial options for the entire toolkit, please refer to the main toolkit organization page. |
0 commit comments