api_network_kit 1.0.3 copy "api_network_kit: ^1.0.3" to clipboard
api_network_kit: ^1.0.3 copied to clipboard

A scalable Flutter package featuring a reusable API client (api_kit) for robust HTTP handling using Dio.

api_network_kit #

A powerful, feature-rich HTTP client for Flutter and Dart applications built on top of Dio. api_network_kit provides a clean, reusable API client with robust error handling, automatic retry mechanisms, connectivity checking, logging, caching, and more.

Features #

  • Generic Response Parsing: Automatic parsing of JSON responses directly to your models.
  • Comprehensive Error Handling: Custom exceptions for all HTTP status codes (e.g. 401, 403, 404, 500).
  • Automatic Retry: Configurable retry logic with exponential backoff for network/gateway errors.
  • Connectivity Verification: Automatic network check before requests, throwing a specific offline exception if no connection is active.
  • Logging: Configurable log levels with formatted terminal output.
  • Token Management: Simple, dynamic authorization header update and removal.
  • Pagination: Built-in support and parsing structures for paginated endpoints.
  • Response Caching: In-memory response caching for GET requests with configurable expiration.
  • Flexible Interceptors: Dynamic hooks for custom request, response, and error modification.
  • File Upload/Download: Simple methods to transfer files with progress callbacks.

Installation #

Add this dependency to your project's pubspec.yaml file:

dependencies:
  api_network_kit: ^1.0.2

Then run:

flutter pub get

Quick Start #

Basic Setup #

import 'package:api_network_kit/api_network_kit.dart';

final api = ApiKit(baseUrl: 'https://api.example.com');

GET Request with Automatic Parsing #

// Define your model
class User {
  User({required this.id, required this.name, required this.email});
  
  factory User.fromJson(Map<String, dynamic> json) => User(
    id: json['id'] as int,
    name: json['name'] as String,
    email: json['email'] as String,
  );
  
  final int id;
  final String name;
  final String email;
}

// Make the request
final user = await api.get<User>(
  '/users/1',
  parser: User.fromJson,
);

POST Request #

final newUser = await api.post<User>(
  '/users',
  data: {
    'name': 'John Doe',
    'email': 'john.doe@example.com',
  },
  parser: User.fromJson,
);

Error Handling #

try {
  final user = await api.get<User>('/users/1', parser: User.fromJson);
} on UnauthorizedException {
  print('Please log in again.');
} on NoInternetException {
  print('Please check your internet connection.');
} on TimeoutException {
  print('Request timed out.');
} on NotFoundException {
  print('User not found.');
} on Exception catch (e) {
  print('An error occurred: $e');
}

Advanced Configurations #

Cache & Retry Settings #

final api = ApiKit(
  baseUrl: 'https://api.example.com',
  token: 'your-initial-auth-token',
  maxRetries: 3,
  retryDelayBase: 1000, // base delay in ms for exponential backoff
  checkConnectivity: true,
  useCache: true,
  cacheMaxAge: 300, // cache expiration in seconds (5 minutes)
  connectTimeout: 30000,
  receiveTimeout: 30000,
  sendTimeout: 30000,
);

Dynamic Token Updates #

// Update token on login
api.updateToken('new-user-token');

// Clear token on logout
api.clearToken();

Interceptors #

api.addInterceptor(
  onRequest: (options) async {
    options.headers['X-Custom-Header'] = 'custom-value';
    return options;
  },
  onResponse: (response) async {
    print('Response status: ${response.statusCode}');
    return response;
  },
  onError: (error) async {
    print('Request failed: ${error.message}');
    return error;
  },
);

API Reference #

Requests #

  • get<T>() / getPaginated<T>()
  • getMap() / getList() / getRaw()
  • post<T>() / postMap() / postList()
  • put<T>() / delete<T>()
  • uploadFile<T>() / downloadFile()

Exceptions #

  • NetworkException, ServerException, NoInternetException, TimeoutException, ApiException
  • BadRequestException (400), UnauthorizedException (401), ForbiddenException (403), NotFoundException (404), ConflictException (409), TooManyRequestsException (429)

For a complete set of features, check the example directory for detailed implementations.

7
likes
0
points
584
downloads

Publisher

unverified uploader

Weekly Downloads

A scalable Flutter package featuring a reusable API client (api_kit) for robust HTTP handling using Dio.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

connectivity_plus, dio, flutter, flutter_bloc, logger

More

Packages that depend on api_network_kit