所以我有这段代码:
getAllDiscussionsFromDb() async {
List<Discussion> discussionsToReturn = [];
List<Discussion> returnDiscussions(var args){
return discussionsToReturn;
}
var discussionsFromDb = await database.query("select * from discussions");
// We have to instantiate actual discussion objects from the database columns
return discussionsFromDb.forEach((discussion) async {
int discussionId = discussion[4];
var comments;
comments = await getCommentsOfDiscussion(discussionId);
discussionsToReturn.add(new Discussion(discussion[0], discussion[1], discussion[2], discussion[3], comments));
}).then(returnDiscussions);
}
唯一的问题是comments = ... line。
这是getCommentsOfDiscussion函数:
getCommentsOfDiscussion(id) async {
List<SingleComment> allComments = [];
List<SingleComment> returnComments(var args) {
return allComments;
}
var commentsFromDb = await database.query("select * from comments where discussionId = $id");
// We have to instantiate actual SingleComment objects from the database columns
return commentsFromDb.forEach((comment) async {
allComments.add(new SingleComment(comment[0], comment[1], comment[2], comment[3]));
}).then(returnComments);
}
如果我用comments = []替换comments = await ...,我的代码完全正常。 await必定存在某种错误。我尝试使用.then而不是等待,但后来我收到一个错误,我无法使用null调用。
提前致谢。
答案 0 :(得分:4)
这一行return discussionsFromDb.forEach((discussion) async {
看起来很奇怪。 forEach
未返回Future
,而是返回void
。
因此).then(returnDiscussions);
无效。
也许
await for(var discussion in discussionsFromDb) {
int discussionId = discussion[4];
var comments;
comments = await getCommentsOfDiscussion(discussionId);
discussionsToReturn.add(new Discussion(discussion[0], discussion[1], discussion[2], discussion[3], comments));
}
return discussionsToReturn;
是你想要的