firebase - Flutter + Cloud firestore + Closures:为什么我可以将文档打印到控制台,但不能添加到列表中?
问题描述
所以我有一个非常复杂的函数,有很多闭包。
我正在使用 Cloud Firestore 检索一些 userId,然后我尝试从 Cloud Firestore 获取 userData。
问题发生在以下代码的最后一行:
List matchList = List();
await CloudFunctions.instance.getHttpsCallable(functionName: 'getUserIdsForSomePurpose',).call(<String, dynamic>{'userId': 'RANDOMUSERID'}).then(
(result) => result.data.forEach(
(matchId) async => await Firestore.instance.collection('users').where('id', isEqualTo: matchId.toString()).getDocuments().then(
(matchQuery) => matchList.add(matchQuery.documents[0].data.toString()))));
即使我尝试打印 的长度matchList
,我也会收到以下错误:
E/flutter ( 6156): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
E/flutter ( 6156): #0 List.[] (dart:core-patch/growable_array.dart:147:60)
E/flutter ( 6156): #1 MatchLogic.loadEventsIntoList (package:nsome/App/Matching/MatchLogic.dart:18:20)
如果我将上面代码的最后一行更改为以下内容(例如,我将数据打印到控制台中),它会以某种方式工作,并且我会将所有数据写入控制台:
(matchQuery) => print(matchQuery.documents[0].data.toString()))));
有人可以帮忙吗?
解决方案
我在创建颤振应用程序时遇到了类似的问题。虽然我不能真正解释为什么,但这是我的解决方案:
List matchList = List();
_createNewFunction (List matchList) {
await CloudFunctions.instance.getHttpsCallable(functionName: 'getUserIdsForSomePurpose',).call(<String, dynamic>{'userId': 'RANDOMUSERID'}).then(
(result) => result.data.forEach(
(matchId) async => await Firestore.instance.collection('users').where('id', isEqualTo: matchId.toString()).getDocuments().then(
(matchQuery) => matchList.add(matchQuery.documents[0].data.toString()))));
}
// run newly created function when you want to use it
_createNewFunction(matchList);
print(matchList.length) // should != 0 (if data is added successfully)
因此,与其添加到“then”函数内的列表中,不如将“matchList”作为参数传递给新创建的函数。这应该可以工作:)
推荐阅读
- json - NLog 数据库参数 + .NET Core:JSON 中的所有事件属性?
- azure - Azure DevOps Pipeline 更改服务结构应用程序的证书权限
- oauth-2.0 - Microsoft Graph API 预订 - 此请求的授权已被拒绝
- python - 找出所有非零值并得到它们的区间
- python - TypeError:给定代码中的“int”和“str”实例之间不支持“<”
- python - 为什么限制功能无法正常工作?
- javascript - 首先获取对象中的最小数字
- sql - 何时在 SQL 中将 *either* "IS" 或 "=" 与 WHERE 子句一起使用
- java - 在使用 Spring Boot 初始化之后发出请求
- python - 观看反应技巧缓存