패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.0.0

flutter_api_helper

간단한 GET 요청부터 복잡한 오류 처리, 캐싱 및 토큰 관리까지 모든 것을 처리하는 강력하고 사용하기 쉬운 Flutter용 API 도우미입니다.

AndroidiOSmacOSWindowsLinux
30일 다운로드
37
좋아요
17
Pub 점수
140

패키지 설치

flutter pub add flutter_api_helper

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

GET, POST 및 기타 메서드를 내장된 지원으로 HTTP 요청을 간소화하는 Flutter용 포괄적인 API 도우미입니다. 오류 관리, 응답 캐싱 및 토큰 인증을 원활하게 처리합니다. 여러 플랫폼에서 네트워크 작업의 반복 코드를 줄이고 신뢰성과 성능을 향상시키기 위해 설계되었습니다.

사용 사례

  • Flutter 앱에서 REST API 호출하기
  • 실패한 요청에 대해 자동 재시도 로직 구현하기
  • 요청 간 인증 토큰 관리
  • 로드 시간을 줄이기 위해 API 응답을 캐시합니다
  • 일관되게 다양한 HTTP 상태 코드 처리하기

주요 기능

  • 내장된 오류 처리 및 재시도 메커니즘
  • 요청/응답 캐싱 지원
  • 자동 토큰 관리 및 새로 고침
  • 간단하고 직관적인 API 인터페이스
  • 크로스 플랫폼 호환성

적합한 대상

  • 자주 API 상호작용을 하는 앱을 개발하는 개발자
  • 클린하고 유지보수 가능한 네트워크 코드를 우선시하는 팀
  • 강력한 오류 복구가 필요한 프로젝트
  • 보안 토큰 처리가 필요한 앱
  • 다중 플랫폼을 대상으로 하는 Flutter 애플리케이션

고려 사항

  • 사용자 정의 헤더 또는 복잡한 인증 흐름을 위해 추가 설정이 필요할 수 있습니다
  • 기본 사용 예제를 넘어서는 문서가 제한적입니다
  • 단순한 요청만 필요한 경우 잠재적인 오버헤드가 발생할 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

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!

카테고리

의존성

의존성 목록 4 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.