Resources are special Signals 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.
Future-based constructor:
Resource(
Future<T> Function() fetcher, {
SignalBase<dynamic>? source,
String? name,
bool? equals,
bool? autoDispose,
bool? trackInDevTools,
bool lazy = true,
});Stream-based constructor:
Resource.stream(
Stream<T> Function() stream, {
SignalBase<dynamic>? source,
String? name,
bool? equals,
bool? autoDispose,
bool? trackInDevTools,
bool lazy = true,
});fetcher is the function that returns a Future.
stream is the function that returns a Stream.
source is the query to the async data fetcher or stream function that triggers the resource everytime it changes.
the other parameters are the options of the resource.
// 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(fetchUser, source: userId);In the example above, just changing the userId value will trigger the Resource again.
Returns the current state of the resource. See ResourceState for more details.
Returns the previous state of the resource. See ResourceState for more details.
Forces a refresh of the resource.
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.
Returns a future that completes with the value when the Resource is ready If the resource is already ready, it completes immediately.
Calls a function with the current [state] and assigns the result as the new state.