如何在 flutter 中将 Future<List> 转换为 List?

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

我正在使用一个名为 search_widget 的 flutter 插件。 此小部件的数据参数采用列表。但是当我使用 sqlite 来获取数据时,我的数据是 Future<List> 形式。 有什么方法可以将 Future<List> 转换为 List? 或任何其他方式使它正常工作。

List list = await _fetchList();

假设 _fetchList() 类似于:

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

假设这是你的返回函数 dataList(),它是未来的:

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

借用 search_widget 的示例,您需要 dataList 在这样的小部件中:

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

当然,您可以像其他答案建议的那样将 Future<List> 转换为 List。但是你不会能够做到dataList: await _sqliteCall();,因为build方法被设计为纯粹和同步的。

当 Future 完成时,您将需要 return 进度指示器之类的东西。为此,您可以使用 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();
  }
),

当然这也可以用StatefulWidget来完成,你可以查看this article for a detailed explanation of the issue.

使用 await 关键字将等待 Future 完成,一旦你的 Future 被执行,它的结果将返回给你。

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

要使其正常工作,您调用的方法应为 async

希望对您有所帮助,如有疑问请评论。

这就是我解决问题的方法...

初始版本:

  @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;
  }

已清理 up/final 版本:

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

future return of apiservice type (Future list). we use key word (then) then future type store to var result as list.

您应该调用 then 的 {} 值,如下所示:

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