FutureProvider的用例 [英] Use case for FutureProvider

查看:720
本文介绍了FutureProvider的用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道FutureProvider类有什么用例?

I was wondering what use case exists for the FutureProvider class?

当使用FutureProviderChangeNotifierProvider或类似的东西构建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和可变对象(ChangeNotiferState)来处理更新.

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 a Future into something easier to manipulate:
    • ChangeNotifierProvider(
        builder: (_) => Foo(),
        child: Consumer<Foo>(
          builder: (_, foo, __) {
            return FutureProvider.value(
              value: foo.someFuture,
              child: ...,
            );
          },
        ),
      );
      

      这篇关于FutureProvider的用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆