api_response 0.2.3 copy "api_response: ^0.2.3" to clipboard
api_response: ^0.2.3 copied to clipboard

A library to hold the instance for a data class that offers different states of an API response making it easier to map.

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.

1
likes
145
points
700
downloads

Publisher

verified publisherbettersuite.io

Weekly Downloads

A library to hold the instance for a data class that offers different states of an API response making it easier to map.

Homepage

Documentation

API reference

License

MIT (license)

Dependencies

dartz, freezed_annotation, json_annotation

More

Packages that depend on api_response