I am creating a stream of a Dart Data Class by accessing data from Firebase Firestore. Inside a block it is showing correct output but outside that block it is printing empty Map. I declared the map outside that block. Please refer the code snippet..
Stream<Map<UserModel?, double>> getFriendStream() {
UserModel user;
return firestore
.collection('users')
.doc(auth.currentUser?.phoneNumber)
.snapshots()
.asyncMap((event) {
Map<UserModel?, double> friendObjectList = new Map();
if (event.data() != null) {
user = UserModel.fromMap(event.data()!);
user.friendList.forEach((key, value) async {
UserModel? doc = await getUserData(key);
// print(key);
// print(doc!.name);
friendObjectList[doc] = value;
// print(friendObjectList); Here it prints Map correctly
});
}
print(friendObjectList); // printing empty Map {}.
return friendObjectList;
});
}
I tried to add some data to a map. I declared it in higher scope and added items in lower space. and return it at higher scope. In higher scope, when I am printing it is giving Empty map but in lower scope, it gives correct Map.