首页 > 解决方案 > 你如何在flutter中通过云功能从firestore获取documentSnapshot?

问题描述

首先进行一些介绍,我需要获取 documentSnapshot 而不仅仅是 Firestore 中记录的数据,因为我的应用程序中有分页,并且要做到这一点,当您查询时,您需要从您的位置发送最后一个 documentSnapshot查询将发送 10 条下一条记录。

因此,这与 SDK 配合得很好,但我现在想实现 Cloud Functions,当我尝试使用来自云函数的 documentSnapshot 进行响应时,我无法在 Flutter 中获取 documentSnapshot。

这是问题所在的代码部分:

final function = _cloudFunctions.getHttpsCallable(
  functionName: 'createRecord',
);
try {
  final response = await function.call(data);
  final DocumentSnapshot doc = response.data;
  return doc;
} catch (e) {
  print(e)
  return null;
}

这段代码我得到错误:类型'_InternalLinkedHashMap'不是'DocumentSnapshot'类型的子类型

有解决方法还是我做错了什么?

标签: flutterdartgoogle-cloud-firestoregoogle-cloud-functions

解决方案


来自可调用云函数的响应不会是强类型DocumentSnapshot。这就是错误消息试图告诉您的内容。你得到一个地图类型的对象,你必须像这样处理那个对象。你不能强迫它成为一个 DocumentSnapshot。

如果您将可调用函数用作分页工具,您将无法在客户端和函数之间来回传递 DocumentSnapshot 对象。您将不得不在不提供 DocumentSnapshot 的情况下向函数传递足够的信息来进行分页。

分页实际上不需要 DocumentSnapshot - 您需要的是足够的信息来告诉查询从中断的地方继续,如文档中所示。这涉及使用 startAt 或 startAfter 使用上一次看到的文档中的信息。


推荐阅读