简体   繁体   中英

How to convert Future<List> to List in flutter?

I am using a plugin for flutter called search_widget . The data parameter of this widget takes a list. But as I use sqlite for fetching data, I have it in Future<List> form. Is there any way I can convert Future<List> to List ? Or any other way to get this working.

List list = await _fetchList();

假设_fetchList()是这样的:

Future<List> _fetchList() {...}

Using await keyword will wait for Future to get completed and once your Future is executed it's result will be returned to you.

import 'dart:async';

void main() async {
  Future<List> _futureOfList = _getList();
  List list = await _futureOfList ;
  print(list); // will print [1, 2, 3, 4] on console.
}

Future<List>  _getList(){
  return Future.value([1,2,3,4]);
}

for this to work, the method where you are calling should be async

I hope this helps, in case of any doubt please comment.

Borrowing the example from search_widget you need dataList in a widget like this:

SearchWidget<LeaderBoard>(
   dataList: list,
   textFieldBuilder: (TextEditingController controller, FocusNode focusNode) {
     return MyTextField(controller, focusNode);
   },
 )

Sure, you can convert Future<List> into List like other answers suggest. But you won't be able to do dataList: await _sqliteCall(); because build methods are designed to be pure and sychronous.

While the Future completes you will have to return something like a progress indicator. For that you can use a FutureBuilder :

FutureBuilder<List<Leaderboard>>(
  future: _sqliteCall(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return SearchWidget<LeaderBoard>(
        dataList: snapshot.data,
        textFieldBuilder: (TextEditingController controller, FocusNode focusNode) {
          return MyTextField(controller, focusNode);
        },
      )
    }
    return CircularProgressIndicator();
  }
),

Of course this can also be done with a StatefulWidget , you can checkthis article for a detailed explanation of the issue .

assuming this is ur returning function dataList() which is Futur :

 List yourlist = new List();
   dataList().then((resultat){
          setState(() => yourlist.add(resultat); 
        });

Thats how I have solved the problem...

Initial version:

  @override
  List<Product> getAll() {
    List<Product> _listProducts;
    Future<List<Product>> listFuture;
    listFuture = _repo.getAll();
    listFuture.then((value) {
      if (value != null) value.forEach((item) => _listProducts.add(item));
    });
    return _listProducts == null ? [] : _listProducts;
  }

Cleaned up/final version:

  @override
  List<Product> getAll() {
    List<Product> _listProducts;
    _repo.getAll().then((value) {
      if (value != null) value.forEach((item) => _listProducts.add(item));
    });
    return _listProducts == null ? [] : _listProducts;
  }
 List<Future<dynamic>> _selectedItems = List<Future<dynamic>>();
    List<dynamic> listofimg = [];
                                    _selectedItems.forEach((element) {
                                      element.then((value) => listofimg.add(value));
                                    });

You should call value on {} of then as below:

onPressed: () {
 _apiService.getProductList().then((result) {
    print(result);
    print("kkkkkkkk:"+result.length.toString());
    for   (var item in result){
    _dsSanpham.add(item);

    }
    Navigator.push(
    context,
    MaterialPageRoute(
        builder: (context) => nhaphangle(
            username: username, dshangle: dshangle, dssanpham: _dsSanpham)),);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM