apix 1.3.0
apix: ^1.3.0 copied to clipboard
Production-ready Flutter/Dart API client with auth refresh queue, exponential retry, smart caching and error tracking (Sentry-ready). Powered by Dio.
/// Apix Example
///
/// This example demonstrates the basic usage of the apix package,
/// including SecureTokenProvider for secure token storage.
library;
import 'package:apix/apix.dart';
import 'package:flutter/material.dart';
/// Simple example showing API client creation and usage.
void main() async {
// ============================================================
// SECURE TOKEN STORAGE
// ============================================================
// SecureTokenProvider uses flutter_secure_storage under the hood
final tokenProvider = SecureTokenProvider();
// Create an API client with authentication and retry
final client = ApiClientFactory.create(
baseUrl: 'https://api.example.com',
connectTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 30),
// Authentication configuration (v1.0.1+)
authConfig: AuthConfig(
tokenProvider: tokenProvider,
// Simplified refresh flow (recommended)
refreshEndpoint: '/auth/refresh',
onTokenRefreshed: (response) async {
final data = response.data as Map<String, dynamic>;
await tokenProvider.saveTokens(
data['access_token'] as String,
data['refresh_token'] as String,
);
},
),
// Retry configuration (v1.0.1+)
retryConfig: const RetryConfig(
maxAttempts: 3,
retryStatusCodes: [500, 502, 503, 504],
),
// Cache configuration (v1.0.1+)
cacheConfig: CacheConfig(
strategy: CacheStrategy.networkFirst,
defaultTtl: const Duration(minutes: 5),
),
// Logger configuration (v1.0.1+)
loggerConfig: const LoggerConfig(
level: LogLevel.info,
redactedHeaders: ['Authorization'],
),
// Error tracking configuration (v1.0.1+)
errorTrackingConfig: ErrorTrackingConfig(
onError: (Object e,
{StackTrace? stackTrace,
Map<String, dynamic>? extra,
Map<String, String>? tags}) async {
debugPrint('Error captured: $e');
},
),
// Metrics configuration (v1.0.1+)
metricsConfig: MetricsConfig(
onMetrics: (metrics) {
debugPrint(
'API: ${metrics.method} ${metrics.path} - ${metrics.durationMs}ms');
},
),
);
// Make a GET request with typed response
try {
final user = await client.getAndDecode(
'/users/1',
(json) => User.fromJson(json),
);
debugPrint('User: ${user.name}');
} on HttpException catch (e) {
debugPrint('HTTP Error: ${e.statusCode}');
} on NetworkException catch (e) {
debugPrint('Network Error: ${e.message}');
}
// Use Result type for functional error handling
final result = await client.get<Map<String, dynamic>>('/users').getResult();
result.when(
success: (response) => debugPrint('Got ${response.data}'),
failure: (error) => debugPrint('Error: ${error.message}'),
);
// ============================================================
// TOKEN MANAGEMENT
// ============================================================
// After login, save tokens
await tokenProvider.saveTokens('access_token_here', 'refresh_token_here');
// Access underlying storage for other secrets
await tokenProvider.storage.write('firebase_token', 'firebase_token_here');
// On logout, clear tokens
await tokenProvider.clearTokens();
// Clean up
client.close();
}
/// Example user model.
class User {
final int id;
final String name;
final String email;
User({required this.id, required this.name, required this.email});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
email: json['email'] as String,
);
}
}