Resource
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.
The contents of the function can be anything. You can hit typical REST endpoints or GraphQL or anything that generates a future or a stream. Resources are not opinionated on the means of loading the data, only that they are driven by futures and streams.
Let’s create a Resource:
// Using http as a clientimport 'package:http/http.dart' as http;
// The sourcefinal userId = Signal(1);
// The fetcherFuture<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);
A Resource can also be driven from a Stream
instead of a Future
, and can be created with Resource.stream(() => stream)
.
The resource has a value named ResourceState
, 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 theResourceState
data classmaybeMap
equal tomaybeOn
but gives access to theResourceState
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
upcastResourceState
into aResourceReady
, or return null if theResourceState
is in loading/error stateasError
upcastResourceState
into aResourceError
, or return null if theResourceState
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 refresh
methods.
The refresh
method forces an update and calls the fetcher
function again or subscribes again to the stream
.