在如下场景中,如何传递一个变量List<Document> itemList
通过引用?
Future.wait([futDocs]).then((dataRet){
dataRet.forEach((doco) {
var docList = doco.documents;
docList.forEach((doc){
var docTitle = doc['title'];
print("data is $docTitle");
itemList.add(docTitle); <--- change not reflected outside this function
itemList
itemList.add(docTitle)
时不会改变在上面的Future.wait()中执行。我相信原因是因为 itemList
不通过引用传递。如果我不能通过 itemList
通过引用,我怎样才能使这项工作?我可以返回吗dataRet
作为列表并在外部使用 Future.wait()
?
正在添加更多信息...
上述调用是在 class ListBuilder
的构造函数中执行的如下代码所示:
class ListBuilder {
List<Document> itemList = new List<Document>();
ListBuilder(){
var futDocs = Firestore.instance.collection('Data').orderBy('time').limit(10).getDocuments();
Future.wait([futDocs]).then((dataRet) {
dataRet.forEach((doco) {
var docList = doco.documents;
docList.forEach((doc){
var docTitle = doc['title'];
print("data is $docTitle");
itemList.add(docTitle); <--- change not reflected outside this function
[...]
在等待答案的过程中,我尝试了自定义 setter 和 getter 以及使用 this.itemList.add(...)
但没有成功。
任何帮助,非常感谢。 提前致谢!
最佳答案
Dart 中的所有对象都是通过引用传递的。
问题可能是 [itemList] 没有立即更新,因为 Future.wait 是一个异步函数。任何处理 itemList 的代码都必须在回调函数 ( .then((dataret) { ... }));
中运行。
class ListBuilder {
List<Document> itemList = new List<Document>();
ListBuilder() {
var Docs =
Firestore.instance.collection('Data').orderBy('time').limit(10).getDocuments();
Future.wait([futDocs]).then((dataRet) {
dataRet.forEach((doco) {
var docList = doco.documents;
docList.forEach((doc) {
var docTitle = doc['title'];
itemList.add(docTitle);
});
});
/*
itemList has been updated here because we are inside a callback function that
runs _after_ Future.wait has completed.
*/
});
/*
itemList hasn't been updated here _yet_ because this code runs immediately,
regardless how long the Future.wait call takes to complete.
*/
}
}
如果您愿意,可以使用异步/等待逻辑而不是回调函数,后者通常更易于阅读和维护。更多信息在这里:https://www.dartlang.org/tutorials/language/futures
关于dart - Flutter Dart : Future. wait() 通过引用传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53510985/