net_kit 5.3.1
net_kit: ^5.3.1 copied to clipboard
Netkit is a library that provides a set of tools to work with network requests.
Contents #
๐ฝ Click to expand
Features #
- ๐ Automatic token refresh with queue-safe retry
- โ๏ธ
onBeforeRefreshRequestto mutate refresh payload - ๐ Parsing responses into models or lists using
INetKitModel - ๐งช Configurable base URLs for development and production
- ๐ Internationalization support for error messages
- ๐ฆ Multipart upload support
- ๐ Extensible logger integration
Sponsors #
A big thanks to our awesome sponsors for keeping this project going!๏ธ Want to help out? Consider becoming a sponsor!
|
|
|
|
Getting started #
Initialize #
Initialize the NetKitManager with the parameters:
import 'package:net_kit/net_kit.dart';
final netKitManager = NetKitManager(
baseUrl: 'https://api.<URL>.com',
devBaseUrl: 'https://dev.<URL>.com',
// ... other parameters
);
Extend the model #
Requests such as: requestModel andrequestList require the model to
extend INetKitModel in order to be used with the NetKitManager. By extending, INetKitModel
fromJson and toJson methods will be needed to be implemented, so the model can be serialized and
deserialized.
class TodoModel extends INetKitModel {}
Custom Void Models in Uploading #
โ ๏ธ Custom Void Models: If you want to handle endpoints that return no data (i.e., void/empty responses) using your own model, your model must implement VoidModel from this package.
Example:
class AppVoidModel implements INetKitModel, VoidModel {
@override
Map<String, dynamic> toJson() => {};
@override
AppVoidModel fromJson(Map<String, dynamic> json) => AppVoidModel();
}
Without implementing VoidModel, void requests will not be recognized correctly and may throw exceptions.
Sending requests #
NetKitManager provides several methods for making HTTP requests. Each method is designed for specific use cases and response types.
Available Request Methods #
| Method | Description | Use Case |
|---|---|---|
requestModel |
Request a single model | Get a single resource |
requestList |
Request a list of models | Get multiple resources |
requestVoid |
Send a request without expecting data | Delete, update operations |
requestModelMeta |
Request a model with metadata | Get a resource with additional info |
requestListMeta |
Request a list with metadata | Get paginated data with metadata |
uploadMultipartData |
Upload a single file | File uploads |
uploadFormData |
Upload form data | Form submissions with files |
Request Examples #
- ๐ Request a Single Model โ
- ๐ Request a List of Models โ
- ๐ Send a Void Request โ
- ๐ Request Model with Metadata โ
- ๐ Request List with Metadata (Pagination) โ
- ๐ Upload Multipart Data (Single File) โ
- ๐ Upload Form Data โ
Why DataKey is Used #
Many APIs return responses in a wrapped format where the actual data is nested under a specific key. For example:
{
"success": true,
"data": {
"id": 1,
"name": "John Doe",
"email": "john@example.com"
},
"message": "User retrieved successfully"
}
Without DataKey configuration, you would need to manually extract the data from the data field in every response. NetKit's DataKey feature automatically handles this extraction, making your code cleaner and more maintainable.
DataKey Configuration #
The useDataKey parameter (default: true) allows you to control whether to use the configured dataKey wrapper for individual requests. This is useful when you have different API endpoints that return data in different formats.
- When
useDataKey: true(default): Uses the configureddataKeyto extract data from the response - When
useDataKey: false: Usesresponse.datadirectly, ignoring thedataKeyconfiguration - Note: This parameter has no effect if
dataKeyis not set in the NetKitManager configuration
Available on all request methods: requestModel, requestModelMeta, requestList, requestListMeta, uploadMultipartData, and uploadFormData.
Advanced Examples #
For more detailed examples including pagination, error handling, and real-world use cases, see EXAMPLES.md.
Setting Tokens #
The NetKitManager allows you to set and manage access and refresh tokens, which are essential for authenticated API requests. Below are the methods provided to set, update, and remove tokens.
Setting Access and Refresh Tokens
To set the access and refresh tokens, use the setAccessToken and setRefreshToken methods. The
accessToken token will be added to the headers of every request made by the NetKitManager.
Note: these should be set on every app launch or when the user logs in.
/// Your method to set the tokens
void setTokens(String accessToken, String refreshToken) {
netKitManager.setAccessToken(accessToken);
netKitManager.setRefreshToken(refreshToken);
}
User Logout #
When a user logs out, you should remove the access and refresh tokens using the removeAccessToken
and removeRefreshToken methods.
Example:
/// Method to log out the user
void logoutUser() {
netKitManager.removeAccessToken();
netKitManager.removeRefreshToken();
}
Token Management #
NetKitManager provides comprehensive token management including automatic refresh, secure storage, and RFC-compliant authentication flows.
Quick Token Setup #
final netKitManager = NetKitManager(
baseUrl: 'https://api.example.com',
refreshTokenPath: '/auth/refresh-token',
onTokenRefreshed: (authToken) async {
await secureStorage.saveTokens(
accessToken: authToken.accessToken,
refreshToken: authToken.refreshToken,
);
},
);
Comprehensive Token Management #
For detailed token management documentation including:
- RFC Compliance (OAuth 2.0, Bearer Token, HTTP Authentication)
- Token Refresh Configuration with advanced options
- Secure Token Storage best practices
- Error Handling for token operations
- Security Considerations and best practices
๐ View Complete Token Management Guide โ
Logger Integration #
The NetKitManager uses a logger internally, for example, during the refresh token stages. To add
custom logging, you need to create a class that implements the INetKitLogger interface. Below is
an example of how to create a NetworkLogger class:
You can find the full example
of
NetworkLogger here.
final netKitManager = NetKitManager(
baseUrl: 'https://api.<URL>.com',
logger: NetworkLogger(),
// ... other parameters
);
Migration Guidance #
โก๏ธ For detailed upgrade steps and breaking changes, see the full Migration Guide.
Feature Status #
| Feature | Status |
|---|---|
| Internationalization support for error messages | โ |
| No internet connection handling | โ |
| Basic examples and documentation | โ |
| Comprehensive examples and use cases | โ |
| MultiPartFile upload support | โ |
| FormData upload support | โ |
| Refresh Token implementation (RFC 6749/6750 compliant) | โ |
| Customizable logging with log levels | โ |
| Request retry logic for failed requests | โ |
| Comprehensive test coverage | โ |
| Authentication and token management | โ |
| DataKey configuration with per-request override | โ |
| Pagination support with metadata | โ |
| Service layer pattern examples | โ |
| Repository pattern examples | โ |
| Error handling strategies | โ |
| File upload with wrapper patterns | โ |
| Token management documentation | โ |
Contributing #
Contributions are welcome! Please open an issue or submit a pull request.
License #
This project is licensed under the MIT License.