flutter_async_value 1.0.1
flutter_async_value: ^1.0.1 copied to clipboard
A simple and elegant way to handle async states (loading, data, error) in Flutter apps.
flutter_async_value #
A lightweight Flutter utility for managing asynchronous statesβloading
, data
, and error
βwith a clean and declarative API. It simplifies UI updates when dealing with asynchronous operations like API calls, database queries, or any Future
/Stream
-based data fetching.
β¨ Features #
- Unified Async State: Represent loading, success, and error states with a single
AsyncValue<T>
class. - Declarative UI Building: Use
AsyncBuilder<T>
to render different widgets based on the current state. - Type-Safe and Null-Safe: Leverages Dart's strong typing to prevent common runtime errors.
- Minimal Boilerplate: Reduces repetitive code for handling asynchronous operations in Flutter widgets.
π¦ Installation #
Add the following to your pubspec.yaml
:
dependencies:
async_value_builder: ^0.0.1
Then, run:
flutter pub get
π Getting Started #
1. Define Your Async Operation #
Future<AsyncValue<String>> fetchData() async {
try {
final result = await someAsyncFunction();
return AsyncValue.data(data: result);
} catch (e) {
return AsyncValue.error(error: e);
}
}
2. Use AsyncBuilder
in Your Widget #
AsyncBuilder<String>(
value: asyncValue,
loading: (context) => CircularProgressIndicator(),
data: (context, data) => Text('Result: $data'),
error: (context, error) => Text('Error: $error'),
)
π API Reference #
AsyncValue<T>
#
Represents the state of an asynchronous operation.
AsyncValue.loading()
: Indicates a loading state.AsyncValue.data({required T data})
: Indicates a successful data retrieval.AsyncValue.error({required Object error})
: Indicates an error occurred.
AsyncBuilder<T>
#
A widget that builds its child based on the current AsyncValue<T>
state.
Constructor Parameters:
value
: TheAsyncValue<T>
instance to observe.loading
: Widget to display during the loading state.data
: Widget to display when data is available.error
: Widget to display when an error occurs.
π§ͺ Example #
class ExampleWidget extends StatelessWidget {
final AsyncValue<String> asyncValue;
const ExampleWidget({Key? key, required this.asyncValue}) : super(key: key);
@override
Widget build(BuildContext context) {
return AsyncBuilder<String>(
value: asyncValue,
loading: (context) => CircularProgressIndicator(),
data: (context, data) => Text('Data: $data'),
error: (context, error) => Text('Error: $error'),
);
}
}
π οΈ Contributing #
Contributions are welcome! Please open issues and submit pull requests for any features, bugs, or enhancements.
π License #
This project is licensed under the MIT License. See the LICENSE file for details.