Flutter API Response π
A lightweight Flutter package for handling API responses with elegance. This package provides a clean and type-safe way to manage different states of network calls in your Flutter applications.
Features
- π‘οΈ Type-safe response handling
- π Seamless state management for API calls
- β‘ Reduce boilerplate when dealing with network requests
- π§© Easy integration with existing projects
- π± Compatible with all Flutter platforms
Installation
Add this to your package's pubspec.yaml file:
dependencies:
flutter_api_response: ^1.0.0
Then run:
flutter pub get
Usage
Basic Example
import 'package:flutter_api_response/flutter_api_response.dart';
Future<ApiResponse<User>> fetchUser(int id) async {
try {
// Make network request
final response = await http.get(Uri.parse('https://api.example.com/users/$id'));
if (response.statusCode == 200) {
// Parse and return successful response
final user = User.fromJson(jsonDecode(response.body));
return ApiResponse.success(user);
} else {
// Handle error response
return ApiResponse.error('Failed to load user data');
}
} catch (e) {
// Handle exceptions
return ApiResponse.error('Network error: ${e.toString()}');
}
}
Using in UI with Switch Expression
FutureBuilder<ApiResponse<User>>(
future: fetchUser(1),
builder: (context, snapshot) {
// Using switch expression to handle different response states
return switch (snapshot.data) {
ApiSuccess(data: final user) => UserProfileWidget(user: user),
ApiError(message: final error) => ErrorWidget(message: error),
ApiLoading() => const LoadingIndicator(),
};
},
)
Repository Pattern Example
class UserRepository {
final HttpClient _client;
UserRepository(this._client);
Future<ApiResponse<List<User>>> getUsers() async {
// Start with loading state
ApiResponse<List<User>> response = ApiResponse.loading();
try {
final data = await _client.get('/users');
final users = (data as List).map((json) => User.fromJson(json)).toList();
return ApiResponse.success(users);
} catch (e) {
return ApiResponse.error('Failed to fetch users: ${e.toString()}');
}
}
}
Working with State Management
class UserViewModel extends ChangeNotifier {
ApiResponse<User> _user = ApiResponse.loading();
ApiResponse<User> get user => _user;
Future<void> fetchUserDetails(int userId) async {
_user = ApiResponse.loading();
notifyListeners();
try {
final response = await userRepository.getUserById(userId);
_user = response;
} catch (e) {
_user = ApiResponse.error(e.toString());
}
notifyListeners();
}
}
States
The package includes these core states:
- Initial: Represents the initial state
- Error: Contains error information
- Loading: Represents a loading state
- Success: Contains the successful data response
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.