flutter_api_helper 1.0.0 copy "flutter_api_helper: ^1.0.0" to clipboard
flutter_api_helper: ^1.0.0 copied to clipboard

A powerful, easy-to-use API helper for Flutter that handles everything from simple GET requests to complex error handling, caching, and token management.

Flutter API Helper #

pub package License: MIT GitHub stars Flutter

๐Ÿš€ A powerful, feature-rich HTTP client for Flutter applications

Built-in caching โ€ข Smart retry logic โ€ข Seamless widget integration


โœจ Features Overview #

Flutter API Helper Features

โœ… Simple API - Intuitive methods for all HTTP operations
โœ… Smart Caching - Memory and disk caching with configurable TTL
โœ… Auto Retry - Exponential backoff for failed requests
โœ… Token Management - Automatic token refresh and injection
โœ… File Operations - Upload/download with progress tracking

โœ… Network Aware - Built-in connectivity checking
โœ… Widget Integration - Ready-to-use Flutter widgets
โœ… Type Safe - Full generic type support
โœ… Interceptors - Custom request/response processing
โœ… Error Handling - Comprehensive error types and handling


๐ŸŽฏ Why Choose Flutter API Helper? #

๐Ÿ†š Comparison Built-in HTTP Flutter API Helper
Setup Complex boilerplate โœจ One-line configuration
Caching Manual implementation ๐Ÿง  Smart auto-caching
Retries Custom retry logic ๐Ÿ”„ Exponential backoff
Errors Generic exceptions ๐Ÿ›ก๏ธ Typed error handling
Files Complex multipart ๐Ÿ“ Simple upload/download
Widgets Custom FutureBuilder ๐ŸŽฏ Ready ApiBuilder

๐Ÿš€ Quick Start #

Installation #

Add this to your package's pubspec.yaml file:

dependencies:
  flutter_api_helper: ^1.0.0

Then run:

flutter pub get

โšก 30-Second Setup #

import 'package:flutter_api_helper/flutter_api_helper.dart';

void main() {
  // ๐Ÿ”ง Configure once, use everywhere
  ApiHelper.configure(
    ApiConfig(
      baseUrl: 'https://api.yourapp.com',
      enableLogging: true,
      timeout: Duration(seconds: 30),
      // ๐Ÿง  Smart caching out of the box
      cacheConfig: CacheConfig(duration: Duration(minutes: 5)),
      // ๐Ÿ”„ Auto-retry with exponential backoff
      retryConfig: RetryConfig(maxRetries: 3),
    ),
  );
  
  runApp(MyApp());
}

๐Ÿ“ฑ Usage Examples #

๐ŸŒ Basic HTTP Operations #

// GET request with automatic type casting
final users = await ApiHelper.get<List<User>>('/users');

// POST request with smart error handling
final newUser = await ApiHelper.post('/users', data: {
  'name': 'John Doe',
  'email': 'john@example.com',
});

// PUT request with caching
final updatedUser = await ApiHelper.put('/users/1', 
  data: {'name': 'Jane Doe'},
  cache: CacheConfig(duration: Duration(minutes: 10)),
);

// DELETE request with retry logic
await ApiHelper.delete('/users/1',
  retry: RetryConfig(maxRetries: 5),
);

๐ŸŽฏ Flutter Widget Integration #

Transform your UI with the ApiBuilder widget:

class UsersList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ApiBuilder<List<User>>(
      future: ApiHelper.get('/users'),
      builder: (users) => ListView.builder(
        itemCount: users.length,
        itemBuilder: (context, index) {
          final user = users[index];
          return ListTile(
            leading: CircleAvatar(child: Text(user.name[0])),
            title: Text(user.name),
            subtitle: Text(user.email),
          );
        },
      ),
      loading: Center(child: CircularProgressIndicator()),
      error: (error) => ErrorWidget('Failed to load users: ${error.message}'),
      empty: Center(child: Text('No users found')),
    );
  }
}

๐Ÿ’พ Smart Caching #

// ๐Ÿง  Cache response for 10 minutes
final posts = await ApiHelper.get(
  '/posts',
  cache: CacheConfig(duration: Duration(minutes: 10)),
);

// ๐Ÿ—‘๏ธ Clear cache when needed
await ApiHelper.clearCache();
await ApiHelper.clearCacheForUrl('/posts');

๐Ÿ” Authentication & Token Management #

ApiHelper.configure(
  ApiConfig(
    baseUrl: 'https://api.yourapp.com',
    // ๐Ÿ”‘ Automatic token injection
    getToken: () async => await TokenStorage.getToken(),
    // ๐Ÿ”„ Automatic token refresh
    onTokenExpired: () async => await AuthService.refreshToken(),
  ),
);

๐Ÿ“ File Operations with Progress #

// ๐Ÿ“ค Upload with real-time progress
final file = File('/path/to/image.jpg');
final response = await ApiHelper.uploadFile(
  '/upload',
  file,
  fieldName: 'image',
  fields: {'description': 'Profile picture'},
  onProgress: (sent, total) {
    final percentage = (sent / total * 100).round();
    print('Upload Progress: $percentage%');
  },
);

// ๐Ÿ“ฅ Download with progress tracking
await ApiHelper.downloadFile(
  '/files/document.pdf',
  '/local/path/document.pdf',
  onProgress: (received, total) {
    final percentage = (received / total * 100).round();
    print('Download Progress: $percentage%');
  },
);

๐Ÿ›ก๏ธ Advanced Error Handling #

try {
  final data = await ApiHelper.get('/api/data');
  // Handle success
} catch (e) {
  if (e is ApiError) {
    switch (e.type) {
      case ApiErrorType.network:
        showSnackBar('Check your internet connection');
        break;
      case ApiErrorType.server:
        showSnackBar('Server is temporarily unavailable');
        break;
      case ApiErrorType.timeout:
        showSnackBar('Request timed out. Please try again');
        break;
      case ApiErrorType.authentication:
        redirectToLogin();
        break;
      default:
        showSnackBar('Something went wrong: ${e.message}');
    }
  }
}

๐Ÿ”„ Smart Retry with Exponential Backoff #

final data = await ApiHelper.get(
  '/unstable-endpoint',
  retry: RetryConfig(
    maxRetries: 5,
    retryDelay: Duration(seconds: 2),
    useExponentialBackoff: true, // 2s, 4s, 8s, 16s, 32s
    maxRetryDelay: Duration(seconds: 30),
  ),
);

๐Ÿ”ง Custom Interceptors #

class AuthInterceptor extends ApiInterceptor {
  @override
  Future<void> onRequest(String method, String url, 
      Map<String, String>? headers, dynamic data) async {
    headers?['Authorization'] = 'Bearer ${await getToken()}';
    headers?['User-Agent'] = 'MyApp/1.0';
  }

  @override
  Future<void> onResponse(http.Response response) async {
    if (response.statusCode == 401) {
      await refreshToken();
    }
    // Log analytics
    Analytics.trackApiCall(response.request?.url.toString());
  }
}

// Add the interceptor
ApiHelper.instance.addInterceptor(AuthInterceptor());

โš™๏ธ Configuration #

๐Ÿ“‹ ApiConfig Options #

ApiConfig(
  baseUrl: 'https://api.example.com',           // ๐ŸŒ Base URL for all requests
  defaultHeaders: {'Accept': 'application/json'}, // ๐Ÿ“‹ Default headers
  timeout: Duration(seconds: 30),               // โฑ๏ธ Request timeout
  enableLogging: true,                          // ๐Ÿ“ Enable request/response logging
  getToken: () async => 'your-token',          // ๐Ÿ”‘ Token getter function
  onTokenExpired: () async => refreshToken(),   // ๐Ÿ”„ Token refresh callback
  onError: (error) => handleError(error),      // ๐Ÿšจ Global error handler
  retryConfig: RetryConfig(...),               // ๐Ÿ”„ Default retry configuration
  cacheConfig: CacheConfig(...),               // ๐Ÿ’พ Default cache configuration
)

๐Ÿ’พ Cache Configuration #

CacheConfig(
  duration: Duration(minutes: 5),     // โฐ How long to cache responses
  keyPrefix: 'myapp_',               // ๐Ÿท๏ธ Prefix for cache keys
  useMemoryCache: true,              // ๐Ÿง  Enable in-memory cache
  useDiskCache: true,                // ๐Ÿ’ฝ Enable persistent disk cache
  maxCacheSize: 10 * 1024 * 1024,   // ๐Ÿ“ Maximum cache size (10MB)
)

๐Ÿ”„ Retry Configuration #

RetryConfig(
  maxRetries: 3,                              // ๐Ÿ”ข Maximum retry attempts
  retryDelay: Duration(seconds: 1),           // โฑ๏ธ Initial delay between retries
  useExponentialBackoff: true,                // ๐Ÿ“ˆ Use exponential backoff strategy
  maxRetryDelay: Duration(seconds: 30),       // โฐ Maximum delay between retries
  retryStatusCodes: [408, 429, 500, 502, 503, 504], // ๐Ÿ“‹ HTTP status codes to retry
)

๐Ÿšจ Error Types #

The package provides detailed error classification:

Error Type Description Common Causes
ApiErrorType.network Network connectivity issues No internet, DNS issues
ApiErrorType.timeout Request timeout errors Slow connection, server overload
ApiErrorType.server Server errors (5xx status codes) Internal server error, maintenance
ApiErrorType.client Client errors (4xx status codes) Bad request, unauthorized
ApiErrorType.authentication Authentication/authorization errors Invalid token, expired session
ApiErrorType.parsing JSON parsing errors Malformed response, unexpected format
ApiErrorType.unknown Unclassified errors Unexpected exceptions

๐Ÿงช Testing #

The package is designed to be testable. You can easily mock API responses:

void main() {
  group('API Tests', () {
    test('should fetch users successfully', () async {
      // Mock your API calls here
      final users = await ApiHelper.get<List<User>>('/users');
      expect(users, isA<List<User>>());
      expect(users.isNotEmpty, true);
    });
    
    test('should handle network errors gracefully', () async {
      expect(
        () => ApiHelper.get('/invalid-endpoint'),
        throwsA(isA<ApiError>()),
      );
    });
  });
}

๐Ÿ“ฑ Platform Support #

Platform Status Notes
Android โœ… Full support
iOS โœ… Full support
Web โœ… Full support
macOS โœ… Full support
Windows โœ… Full support
Linux โœ… Full support

๐Ÿ“‹ Requirements #

  • Flutter: >=3.0.0
  • Dart: >=2.17.0

๐Ÿ“š Examples #

For complete examples, check out the example folder which includes:

  • ๐ŸŒ Basic API operations
  • ๐Ÿ” Authentication flow
  • ๐Ÿ“ File upload/download
  • ๐Ÿ’พ Caching strategies
  • ๐Ÿ›ก๏ธ Error handling patterns
  • ๐ŸŽฏ Widget integration examples

๐Ÿค Contributing #

We welcome contributions! Please see our Contributing Guide for details.

๐Ÿ› ๏ธ Development Setup #

  1. ๐Ÿด Fork the repository
  2. ๐ŸŒฟ Create your feature branch (git checkout -b feature/amazing-feature)
  3. ๐Ÿ’พ Commit your changes (git commit -m 'Add amazing feature')
  4. ๐Ÿ“ค Push to the branch (git push origin feature/amazing-feature)
  5. ๐Ÿ”„ Open a Pull Request

๐Ÿ“ Changelog #

See CHANGELOG.md for a detailed history of changes.


๐Ÿ“„ License #

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ“ž Support & Community #

๐Ÿ“– Documentation ๐Ÿ› Issues ๐Ÿ’ฌ Discussions โญ GitHub


๐ŸŽ‰ Made with โค๏ธ for the Flutter community

If this package helped you, please consider giving it a โญ on GitHub!

16
likes
140
points
36
downloads

Publisher

unverified uploader

Weekly Downloads

A powerful, easy-to-use API helper for Flutter that handles everything from simple GET requests to complex error handling, caching, and token management.

Homepage
Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

connectivity_plus, flutter, http, meta, shared_preferences

More

Packages that depend on flutter_api_helper