【问题标题】:Getting length of firestore snapshot in flutter returns "Instance of Future<int>"在颤振中获取firestore快照的长度返回“Future的实例<int>”
【发布时间】:2021-10-23 08:32:34
【问题描述】:

我正在尝试使用 .length.toString 方法返回查询返回的项目的长度,并将字符串响应存储在变量中

final String numberOfChildren = FirebaseFirestore.instance
        .collection("children")
        .where("parentUID", isEqualTo: uid)
        .snapshots()
        .length
        .toString();

当我尝试在像
Text('Children $numberOfChildren'), 这样的文本小部件中使用变量 numberOfChildren 它返回

我以为它会返回一个字符串,为什么会这样呢?

编辑

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    你需要先等待它:

    final String numberOfChildren = await FirebaseFirestore.instance .collection("children")
    .where("parentUID", isEqualTo: uid)
    .get().then((result)=>results.docs.length.toString()); 
    

    【讨论】:

    • 这是否意味着我必须把它作为一个异步函数,因为当我尝试这个时,我无法从函数内部访问变量
    • 绝对是的。
    • 如何从函数内部访问变量
    • 您将其用作函数,或者第二个选项是通过流\未来构建器。
    • 你不能像这样在你的构建方法中使用。将其更改为有状态的小部件,或者如我上面所说的,未来的构建器。如果您决定使用有状态小部件,则需要在函数返回值后设置状态,以更新您的 UI。
    猜你喜欢
    • 2022-01-14
    • 2019-06-28
    • 2021-10-30
    • 2022-11-05
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 2021-08-04
    • 2020-05-12
    相关资源
    最近更新 更多