Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 420
Basel Abuhadrous Avatar asked Jul 11 '19 12:07

Basel Abuhadrous


2 Answers

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());
  }
);
like image 194
Rémi Rousselet Avatar answered Nov 09 '22 15:11

Rémi Rousselet


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),
                    );
                  },
                );
        })));
like image 45
Bruno Camargos Avatar answered Nov 09 '22 14:11

Bruno Camargos