问题
I was wondering what use case exists for the FutureProvider
class?
I am particularly interested how to load an asynchronous function like Future<Contact> getAllContacts() async { ... }
when the ui is built with a FutureProvider
, ChangeNotifierProvider
or anything similar.
Moreover, each time when notifyListeners()
is called, I would like to have that provider to rebuild the ui with asynchronous call. Is that any way possible with provider or am I missing something?
回答1:
FutureProvider
doesn't come with a built-in update mechanism – but can be combined with Consumer
and a mutable object (ChangeNotifer
or State
) to handle updates.
It has two main usages:
- Exposing an "immutable value" that needs to be asynchronously loaded (a config file for example):
FutureProvider<MyConfig>(
builder: (_) async {
final json = await // TODO load json from something;
return MyConfig.fromJson(json);
}
)
- Alternatively, it can be combined with something that can mutate (like
ChangeNotifier
) to convert aFuture
into something easier to manipulate:
ChangeNotifierProvider(
builder: (_) => Foo(),
child: Consumer<Foo>(
builder: (_, foo, __) {
return FutureProvider.value(
value: foo.someFuture,
child: ...,
);
},
),
);
来源:https://stackoverflow.com/questions/57349706/use-case-for-futureprovider