Resources
Resources
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 data, error and loading.
Resources can be driven by a source
signal that provides the query to an async data fetcher
function that returns a Future
.
The contents of the fetcher
function can be anything. You can hit typical REST endpoints or GraphQL or anything that generates a future. Resources are not opinionated on the means of loading the data, only that they are driven by futures.
Let's create a Resource:
// Using http as a client
import 'package:http/http.dart' as http;
// The source
final userId = createSignal(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 = createResource(fetcher: fetchUser, source: userId);
A Resource can also be driven from a [stream] instead of a Future.
In this case you just need to pass the stream
field to the createResource
method.
The [source] field is ignored for the [stream] and used only for a [fetcher].
If you are using the flutter_solidart
library, check ResourceBuilder to learn how to react to the state of the resource in the UI.
The resource has a value named ResourceValue
, that provides many useful convenience methods to correctly handle the state of the resource.
The on
method forces you to handle all the states of a Resource (ready, error and loading).
The are also other convenience methods to handle only specific states:
on
forces you to handle all the states of a ResourcemaybeOn
lets you decide which states to handle and provide anorElse
action for unhandled statesmap
equal toon
but gives access to theResourceValue
data classmaybeMap
equal tomaybeMap
but gives access to theResourceValue
data classisReady
indicates if theResource
is in the ready stateisLoading
indicates if theResource
is in the loading statehasError
indicates if theResource
is in the error stateasReady
upcastResourceValue
into aResourceReady
, or return null if theResourceValue
is in loading/error stateasError
upcastResourceValue
into aResourceError
, or return null if theResourceValue
is in loading/ready statevalue
attempts to synchronously get the value ofResourceReady
error
attempts to synchronously get the error ofResourceError
A Resource
provides the fetch
and refetch
methods.
The refetch
method forces an update and calls the fetcher
function again.