【问题标题】:Convert Future<List> from Firestore to List<String> - Flutter Firebase [duplicate]将 Future<List> 从 Firestore 转换为 List<String> - Flutter Firebase [重复]
【发布时间】:2021-01-21 03:04:46
【问题描述】:

我需要使用来自 Firestore 的列表,但我不知道如何将我从 Firestore 获得的 Future 列表转换为字符串列表:

Future<List> getListOfProducts() async {
    List<String> productsList;
    final List<DocumentSnapshot> documents =
        (await FirebaseFirestore.instance.collection('products').get()).docs;
    productsList = documents
        .map((documentSnapshot) => documentSnapshot['productName'] as String)
        .toList();
    return productsList;
  }

我现在应该如何处理 productList ?

【问题讨论】:

    标签: flutter dart google-cloud-firestore future


    【解决方案1】:

    由于这个函数是异步的,它必须返回一个Future。但是,您可以做的是await 调用函数时的结果。 List&lt;String&gt; lst = await getListOfProducts()

    【讨论】:

    • 我尝试这样做,但我得到“等待表达式只能在异步函数中使用。”错误。
    • 这意味着你在你不能使用的地方非法使用了 await 关键字。您如何/在哪里使用它?
    • 这是我的代码: List myProductsList = await getListOfProducts();
    • 我的意思是你在哪里使用它?您是否在传递给按钮的onPressed 的函数中使用它?你在构造函数中使用它吗?等
    • 现在一切都清楚了,我忘记了主函数中的异步,谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 2021-11-11
    • 1970-01-01
    • 2020-04-16
    • 2019-11-20
    • 2018-08-27
    • 1970-01-01
    • 2022-01-03
    相关资源
    最近更新 更多