我有两个功能, 从Firestore获取用户的第一个。然后,我使用“ Future.ForEach”在这些用户上循环播放。
Future<List> getData() async {
targetData.clear();
await Firestore.instance
.collection('users')
.document(currentUserId)
.collection('chats')
.getDocuments()
.then((userChats) async {
// Only two documents are coming from the db
return await Future.forEach(userChats.documents, getTargetData)
.then((onValue) {
print('forEech is done');
});
});
print('getData Returen');
// I use "targetData" to build viewList
return targetData;
}
从Future.forEach调用此函数
Future<List> getTargetData(DocumentSnapshot targetDoc) async {
print('looping');
await Firestore.instance
.collection('users')
.document(targetDoc.documentID)
.get()
.then((targetRef) {
targetData.add(new TargetUserData(
targetRef.documentID,
targetRef.data['nickname'],
targetRef.data['photoUrl'],
targetDoc.data['timestamp'],
targetRef.data['token'],
targetDoc.data['unseen']));
});
return targetData;
}
我正在从FutureBuilder内部调用getData
return new FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return buildLoading();
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return createListView(context, snapshot);
}
},
);
当我运行该应用程序时,它运行正常,并且符合预期-这是print语句中的日志:
我希望在热加载时得到相同的结果,但是,即将发生的事情!!
问题:为什么forEach的循环次数超出预期?
答案 0 :(得分:0)
我能够通过重新编写代码来解决它:
Future<List> _getData() async {
var allUsers = await Firestore.instance.collection('users').getDocuments();
List<TargetUserData> users = [];
for (var userData in allUsers.documents) {
if (currentUserId != userData.documentID) {
await getTargetData(userData.documentID).then((targetData) {
TargetUserData targetUserData = TargetUserData(
userData.documentID,
userData.data['nickname'],
userData.data['photoUrl'],
targetData[0],
userData.data['token'],
targetData[1],
targetData[2]);
users.add(targetUserData);
});
}
}
return users;
}
Future getTargetData(var targetId) async {
List targetData = [];
await Firestore.instance
.collection('users')
.document(currentUserId)
.collection('chats')
.document(targetId)
.get()
.then((advData) {
if (advData.data != null) {
targetData.add(advData.data['timestamp']);
targetData.add(advData.data['unseen']);
targetData.add(advData.data['lastMsg']);
} else {
targetData.add('0');
targetData.add('0');
targetData.add('Start Chating!');
}
}).catchError((onError) {
print('on error: $onError');
});
return targetData;
}