Resource API docs
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.
Constructors
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://jsonplaceholder.typicode.com/users/${userId.value}/'),
headers: {'Accept': 'application/json'},
);
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.
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.