我有一個存盤用戶資訊的資料庫,例如他們的姓名和所有朋友。資料庫看起來像這樣:
{
"users": {
"userID here": {
"bio": "",
"country": "",
"dateOfBirth": "2022-04-13 17:49:45.906226",
"emergencyContacts": {
"mom": {
"emailAdd": "[email protected]",
"name": "mom",
"phoneNumber": "07492017492",
"picUrl": "url here'"
}
},
"friends": {
"auto-generated ID (used push method)": {
"country": "",
"profilePicUrl": "url here",
"userID": "userID here",
"username": "newOne"
}
},
"fullName": "name",
"gender": "Female",
"hobbies": "[]",
"knownMH": "[]",
"lastMessageTime": "2022-04-14 08:44:40.639944",
}
}
我想訪問該"friends"節點。這樣做時,我還想將資料存盤在二維陣列中。因此,每個子陣列將包含有關我們當前回圈的用戶和他們的一個朋友的資料。這應該會發生,直到我們遍歷了用戶的所有朋友,然后轉到下一個用戶。
這也值得一提;我使用推送方法來添加朋友,所以我得到隨機分配的節點鍵。
我使用了下面的方法,但它不起作用,它回傳了錯誤的朋友串列并且沒有遍歷所有用戶。請在下面找到我使用的代碼(非常感謝任何幫助):
void _retrieveAllFriendships() {
final allUsersDb = FirebaseDatabase.instance.ref().child('users');
_allUserssStream = allUsersDb.onValue.listen((event) {
if (event.snapshot.exists) {
final data = new Map<dynamic, dynamic>.from(
event.snapshot.value as Map<dynamic, dynamic>);
data.forEach((key, value) {
allUsersDb.child(key).onValue.listen((event) {
final acc = new Map<dynamic, dynamic>.from(
event.snapshot.value as Map<dynamic, dynamic>);
final username = acc['username'] as String;
final profilePicUrl = acc['profilePicUrl'] as String;
final country = acc['country'] as String;
final userID = acc['userID'] as String;
user = new FriendSuggestionModel(
picture: profilePicUrl,
name: username,
location: country,
userID: userID,
);
_friendshipStream = allUsersDb
.child(userID)
.child("friends")
.onValue
.listen((event) {
if (event.snapshot.exists) {
final data = new Map<dynamic, dynamic>.from(
event.snapshot.value as Map<dynamic, dynamic>);
data.forEach((key, value) {
allUsersDb
.child(userID)
.child("friends")
.child(key)
.onValue
.listen((event) {
final friend = new Map<dynamic, dynamic>.from(
event.snapshot.value as Map<dynamic, dynamic>);
final username = friend['username'] as String;
final profilePicUrl = friend['profilePicUrl'] as String;
final country = friend['country'] as String;
final userID = friend['userID'] as String;
friendModel = new FriendSuggestionModel(
picture: profilePicUrl,
name: username,
location: country,
userID: userID);
List<FriendSuggestionModel> friendship = [
user,
friendModel
];
allFriendships.add(friendship);
setState(() {
for (int i = 0; i < allFriendships.length; i ) {
print(
"${allFriendships[i][0].name} is friends with: ${allFriendships[i][1].name}");
}
});
});
});
}
});
});
});
}
});
}
uj5u.com熱心網友回復:
當您將偵聽器附加到allUsersDb.onValue 該路徑下的所有資料時,該路徑中已經存在event.snapshot并且您不再需要該資料的任何偵聽器。
如果您知道要訪問的子快照的名稱,您可以通過snapshot.child("friends"). 如果您不知道子快照的名稱,您可以使用snapshot.children.forEach.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459953.html
標籤:火力基地 扑 镖 firebase-实时数据库
上一篇:為什么應用程式下降
