Basel Abuhadrous
Basel Abuhadrous

Reputation: 1650

How to get data from the FutureProvider in 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.

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

Upvotes: 9

Views: 14116

Answers (2)

Bruno Camargos
Bruno Camargos

Reputation: 327

In my example I used the create parameter of FutureProvider to request the API, then then I used Consumer to get the results of the API.

 FutureProvider(
        create: (_) => peopleService.getAllSurvivor(),
        child: Consumer<List<Survivor>>(builder: (context, survivors, _) {
          return survivors == null
              ? Center(child: CircularProgressIndicator())
              : ListView.builder(
                  itemCount: survivors.length,
                  itemBuilder: (context, index) {
                    var survivor = survivors[index];
                    return ListTile(
                      title: Text(survivor.name),
                      subtitle: Text(survivor.gender),
                      leading: Icon(Icons.perm_identity),
                    );
                  },
                );
        })));

Upvotes: 2

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 276997

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

Upvotes: 15

Related Questions