尽管List内部有元素,但List.map仍未执行(颤振) [英] List.map not executing despite List having elements inside(flutter)
问题描述
我正在为这个问题挠头,也许这很明显,但我不确定,我从firestore检索了一个querysnapshot,它返回了一个带有snapshot.docs的querydocumentsnapshot列表,但是当我尝试映射它时,什么也没有发生,如果我在for ... in循环中使用它,则效果会很好.
Hi i am scratching my head over this problem, maybe its something obvious but im not really sure, i retrieve a querysnapshot from firestore, which returns a list of querydocumentsnapshot with snapshot.docs, but when i try to map it nothing happens, if i use a for...in loop it would work perfect.
QuerySnapshot snap =
await FirebaseFirestore.instance.collection('Products').doc(FirebaseAuth.instance.currentUser.uid).collection('ItemDetails').get();
print(snap.docs);//returns [Instance of 'QueryDocumentSnapshot', Instance of 'QueryDocumentSnapshot', Instance of 'QueryDocumentSnapshot']
for (var item in snap.docs.toList()) {//this executes perfectly
print(item.data());
}
snap.docs.toList().map((e) => print(e.data().toString()));//this wont execute
snap.docs.map((e) => print(e.data().toString()));//this wont execute
推荐答案
This is because of the way map
method works. According to the documentation -
map< T>方法
map<T> method
Iterable<T> map <T>(
T f(
E e
)
)
返回带有通过调用创建的元素的新的惰性Iterable按迭代顺序在此Iterable的每个元素上按f.
Returns a new lazy Iterable with elements that are created by calling f on each element of this Iterable in iteration order.
此方法返回映射元素的视图.只要返回的Iterable未迭代,提供的函数f将不被调用.转换后的元素将不会被缓存.反复进行返回的Iterable多次将调用提供的在同一个元素上多次执行f功能.
This method returns a view of the mapped elements. As long as the returned Iterable is not iterated over, the supplied function f will not be invoked. The transformed elements will not be cached. Iterating multiple times over the returned Iterable will invoke the supplied function f multiple times on the same element.
返回的iterable上的方法允许省略对任何方法的调用f不需要结果的元素.例如,elementAt可以调用f只有一次.
Methods on the returned iterable are allowed to omit calling f on any element where the result isn't needed. For example, elementAt may call f only once.
在您的示例中,因为您没有迭代生成的 Iterable
,所以它不会调用该函数.因此,如果您将代码更改为此
In your example, because you are not iterating over the resulting Iterable
, it won't invoke the function. So if you change your code to this
snap.docs.map((e) => print(e.data().toString())).toList();
然后它将执行,因为现在它需要遍历生成的 Iterable
以便将其转换为 List
.
then it will execute because now it needs to iterate over the resulting Iterable
in order to convert it to a List
.
这篇关于尽管List内部有元素,但List.map仍未执行(颤振)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!