GT API

pub package License: MIT

A production-ready Flutter API service package with Dio-based HTTP operations, automatic retry, comprehensive logging, file downloads, and network checking.

Features

  • 🌐 Complete HTTP Methods - GET, POST, PUT, DELETE, PATCH
  • πŸ”„ Automatic Retry - Configurable retry with exponential backoff
  • πŸ“Š Rich Logging - Request/response logging with timing
  • πŸ“₯ File Downloads - Progress tracking and multiple downloads
  • 🌍 Network Checking - Built-in connectivity verification
  • βš™οΈ Configurable - Timeouts, headers, base URLs
  • πŸ›‘οΈ Error Handling - Type-safe ApiException with error types
  • πŸ“¦ Type-Safe Responses - Generic ApiResponse<T> with parsing

Installation

Add to your pubspec.yaml:

dependencies:
  gt_api: ^1.0.0

Then run:

flutter pub get

Quick Start

1. Configure and Initialize

import 'package:gt_api/gt_api.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Configure API
  ApiConfig()
    ..baseUrl = 'https://api.example.com'
    ..enableLogs = true
    ..enableRetry = true
    ..globalHeaders = {'Authorization': 'Bearer token'};
  
  // Initialize
  ApiService().initialize();
  
  runApp(MyApp());
}

2. Make API Calls

final api = ApiService();

// GET request
final response = await api.get<User>(
  '/users/1',
  parser: (json) => User.fromJson(json),
);

if (response.isSuccess) {
  final user = response.data;
  print('User: ${user?.name}');
} else {
  print('Error: ${response.error?.message}');
}

// POST request with body
final createResponse = await api.post(
  '/users',
  data: {'name': 'John', 'email': 'john@example.com'},
);

3. File Downloads

final result = await api.downloadFile(
  url: 'https://example.com/file.pdf',
  onProgress: (received, total) {
    print('Progress: ${(received / total * 100).toStringAsFixed(0)}%');
  },
);

if (result.isSuccess) {
  print('Saved to: ${result.filePath}');
}

4. FormData for Multipart Uploads

final formData = FormDataHelper.createWithFiles(
  fields: {'name': 'Document'},
  filePaths: ['/path/to/file.pdf'],
  fileField: 'document',
);

final response = await api.post('/upload', data: formData);

Configuration Options

ApiConfig()
  ..baseUrl = 'https://api.example.com'
  ..connectTimeout = Duration(seconds: 30)
  ..receiveTimeout = Duration(seconds: 30)
  ..sendTimeout = Duration(seconds: 30)
  ..enableLogs = true
  ..enableRetry = true
  ..retryCount = 3
  ..retryDelay = Duration(seconds: 1)
  ..exponentialBackoff = true
  ..checkInternetBeforeCall = true
  ..globalHeaders = {'Content-Type': 'application/json'}
  ..onUnauthorized = () => navigateToLogin()
  ..globalExceptionHandler = (error) => showErrorDialog(error);

ApiResponse Properties

Property Type Description
isSuccess bool Request succeeded
isError bool Request failed
data T? Parsed response data
raw dynamic Raw response
statusCode int? HTTP status code
error ApiException? Error details
duration Duration? Request duration

ApiException Types

Type Description
noInternet No internet connection
timeout Request timeout
unauthorized 401 Unauthorized
forbidden 403 Forbidden
notFound 404 Not Found
serverError 5xx Server error
cancelled Request cancelled

License

MIT License - see LICENSE for details.