首页 > 解决方案 > 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()))));

有人可以帮忙吗?

标签: firebaseflutterdartgoogle-cloud-firestoredart-async

解决方案


我在创建颤振应用程序时遇到了类似的问题。虽然我不能真正解释为什么,但这是我的解决方案:

    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”作为参数传递给新创建的函数。这应该可以工作:)


推荐阅读