net_kit 5.3.0-dev copy "net_kit: ^5.3.0-dev" to clipboard
net_kit: ^5.3.0-dev copied to clipboard

Netkit is a library that provides a set of tools to work with network requests.

h)

Version License Contributions welcome GitHub Sponsors

Contents #

πŸ”½ Click to expand

Features #

  • πŸ”„ Automatic token refresh with queue-safe retry
  • βš™οΈ onBeforeRefreshRequest to 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!

WESTUDIO VREMICA JURNALLE

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 configured dataKey to extract data from the response
  • When useDataKey: false: Uses response.data directly, ignoring the dataKey configuration
  • Note: This parameter has no effect if dataKey is 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.

5
likes
0
points
1.14k
downloads

Publisher

verified publisherbehzod.dev

Weekly Downloads

Netkit is a library that provides a set of tools to work with network requests.

Repository (GitHub)
View/report issues

Topics

#network #network-manager #remote-data #dio

Funding

Consider supporting this project:

github.com
buymeacoffee.com

License

unknown (license)

Dependencies

dio

More

Packages that depend on net_kit