FutureProvider的用例 [英] Use case for FutureProvider
问题描述
我想知道FutureProvider
类有什么用例?
I was wondering what use case exists for the FutureProvider
class?
当使用FutureProvider
,ChangeNotifierProvider
或类似的东西构建ui时,如何加载像Future<Contact> getAllContacts() async { ... }
这样的异步函数特别使我感兴趣.
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.
此外,每次调用notifyListeners()
时,我都希望该提供程序通过异步调用来重建ui.提供程序有什么可能的方式还是我错过了什么?
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?
推荐答案
FutureProvider
不带有内置的更新机制,但可以与Consumer
和可变对象(ChangeNotifer
或State
)来处理更新.
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.
它有两个主要用法:
- 公开需要异步加载的不可变值"(例如配置文件):
FutureProvider<MyConfig>(
builder: (_) async {
final json = await // TODO load json from something;
return MyConfig.fromJson(json);
}
)
- 或者,它可以与可以变异的东西(例如
ChangeNotifier
)结合使用,以将Future
转换为更易于操纵的东西:- 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: ..., ); }, ), );
这篇关于FutureProvider的用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Alternatively, it can be combined with something that can mutate (like