async_state_builder 0.3.3
async_state_builder: ^0.3.3 copied to clipboard
Implementation of the Future Builder and Stream Builder widgets as state machines.
async_state_builder #
async_state_builder provides widgets for handling asynchronous data using state machines and pattern matching.
This package is an improved version of the standardStreamBuilder
and FutureBuilder
widgets,
making it easier to manage and respond to various states of asynchronous computations.
Benefits of Using State Machines #
Using state machines instead of traditional conditional logic found in StreamBuilder
/FutureBuilder
offers several advantages:
- Readability: Pattern matching provides a clear and concise way to handle various states, making the code easier to read and understand.
- Maintainability: State machines separate state logic from the UI, making the code easier to maintain and extend.
- Reliability: Explicitly defined states reduce the chances of encountering unexpected states or transitions, improving the robustness of your code.
Usage #
StreamStateBuilder #
All states
StreamStateBuilder<int>(
stream: stream,
builder: (BuildContext context, StreamState<int> state) {
return switch (state) {
Waiting() => const Text('Waiting for data...'),
Data<int>(:final data) => Text('Data sent without error: $data'),
Closed<int>(:final data?) => Text('Closed, data received before closing: $data'),
Closed<int>() => const Text('Stream closed, before any data was sent'),
Error<int>(:final data?, :final error) => Text('Error, data received before error: $data. Error: $error'),
Error<int>(:final error) => Text('Error received before any data was sent. Error: $error'),
};
},
),
As with pattern matching, you can code for only the states you care about
switch (state) {
Waiting() => const Text('Waiting for data...'),
Data<int>(:final data) => Text('Data sent without error: $data'),
_ => Text('Unexpected state'),
};
FutureStateBuilder #
All states
FutureStateBuilder<int>(
future: future,
builder: (BuildContext context, FutureState<int> state) {
return switch (state) {
Waiting() => const Text('Waiting for data...'),
Data<int>(:final data) => Text('Future completed without error. Data: $data'),
Error<int>(:final error) => Text('Future completed with error. Error: $error'),
};
},
)