How to get data from the FutureProvider in flutter

后端 未结 2 2132
伪装坚强ぢ
伪装坚强ぢ 2021-02-15 13:21

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 patt

相关标签:
2条回答
  • 2021-02-15 13:56

    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());
      }
    );
    
    0 讨论(0)
  • 2021-02-15 14:10

    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),
                        );
                      },
                    );
            })));
    
    0 讨论(0)
提交回复
热议问题