How to get data from the FutureProvider in flutter

≡放荡痞女 提交于 2020-08-24 07:32:25

问题


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.

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),
              );
            },
          ),
        ),
      ),
    );
  }
}

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


回答1:


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

As such, using the following FutureProvider:

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

it is possible to obtain the current value through:

Provider.of<int>(context)

or:

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


来源:https://stackoverflow.com/questions/56989807/how-to-get-data-from-the-futureprovider-in-flutter

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