如何从Flutter中获取FutureProvider的数据 [英] How to get data from the FutureProvider in flutter

查看:554
本文介绍了如何从Flutter中获取FutureProvider的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在使用Provider管理的flutter应用程序中实现本地数据库支持,现在我想使数据检索服从状态管理模式,但是我一直失败。

I'm trying to implement local database support in my flutter app which is being managed using Provider, now I want to make the retrieving of data obey the state management pattern, but I've been failing to.

我试图创建一个传统的Provider来实现此目的,但是应用程序陷入了对数据库的请求循环中,因此在进行一些搜索之后,我找到了FutureProvider,但是我找不到如何从正在加载的数据中获取快照

I've tried to make a traditional Provider to achieve this but the app got stuck in a loop of requests to the database, so after some search I found the FutureProvider, but I cant find how can I get a snapshot from the data being loaded

class _ReceiptsRouteState extends State<ReceiptsRoute> {
  List<Receipt> receipts = [];

  @override
  Widget build(BuildContext context) {
    return FutureProvider(
      initialData: List(),
      builder: (_){
        return DBProvider().receipts().then((result) {
          receipts = result;
        });
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(AppLocalizations.of(context).history),
        ),
        body: Container(
          child: ListView.builder(
            itemBuilder: (context, position) {
              final item = receipts[position];
              return ListTile(
                title: Text(item.date),
              );
            },
          ),
        ),
      ),
    );
  }
}

现在我的应用程序正在按我的方式运行,但没有如何运行,我使用FutureBuilder直接从数据库中获取数据,但我知道它应该通过提供程序提供,因此我想使其正确

now my app is running as I want but not as how it should run, I used FutureBuilder to get the data from the database directly but I know it should come through the provider so I want to make it right

推荐答案

FutureProvider 公开了 builder返回的 Future 的结果/ code>为其后代。

FutureProvider exposes the result of the Future returned by builder to its descendants.

因此,使用以下 FutureProvider

FutureProvider<int>(
  initialData: 0,
  builder: (_) => Future.value(42),
  child: ...
)

可以通过以下方式获取当前值:

it is possible to obtain the current value through:

Provider.of<int>(context)

或:

Consumer<int>(
  builder: (context, value, __) {
    return Text(value.toString());
  }
);

这篇关于如何从Flutter中获取FutureProvider的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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