Use case for FutureProvider

☆樱花仙子☆ 提交于 2020-06-13 00:30:51

问题


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 a Future 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!