2017-04-15 36 views
1

所以我有這樣的代碼:飛鏢 - 未來幾年內前景不正常

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); 
} 

與它唯一的問題是意見= ...行。

這是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); 
} 

如果我更換=等待......與評論的評論= [],我的代碼工作完全正常。等待時肯定會有某種錯誤。我嘗試使用.then而不是等待,但然後我得到一個錯誤,我不能使用null調用。

在此先感謝。

回答

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; 

是你想要

+0

作品完美的東西,謝謝 – OhMad