Resource API docs
Resource
s are special Signal
s designed specifically to handle Async
loading. Their purpose is wrap async values in a way that makes them easy
to interact with handling the common states of a future or stream data, error and loading.
A Resource extends a Signal, so all the API of Signal are available.
Constructor
Resource({
Future<T> Function()? fetcher,
Stream<T>? Function()? stream,
ResourceOptions? options,
SignalBase<dynamic>? source,
});
fetcher
is the function that returns a Future
.
stream
is the function that returns a Stream
.
options
are the options of the resource.
source
is the query to the async data fetcher
or stream
function that triggers the resource everytime it changes.
// Using http as a client, you can use any other client
import 'package:http/http.dart' as http;
// The source
final userId = Signal(1);
// The fetcher
Future<String> fetchUser() async {
final response = await http.get(
Uri.parse('https://swapi.dev/api/people/${userId.value}/'),
);
return response.body;
}
// The resource (source is optional)
final user = Resource(fetcher: fetchUser, source: userId);
In the example above, just changing the userId
value will trigger the Resource
again.
ResourceState<T> get state
Returns the current state of the resource. See ResourceState for more details.
ResourceState<T> get previousState
Returns the previous state of the resource. See ResourceState for more details.
Resource<Selected> select<Selected>(Selected Function(T data) selector, { String? name })
Filters the Resource
's data by reading only the properties that you care about.
The advantage is that you keep handling the loading and error states.