【发布时间】:2021-11-20 00:10:44
【问题描述】:
我正在尝试为我的应用创建排行榜功能,我需要按他们的分数对 firebase 用户列表进行排序,并且只显示最接近我的用户分数的前五名用户。每当我尝试对它们进行排序时遇到问题(分数,isLessThanOrEqualTo:用户分数)它无法正确获得分数。
这是错误信息。
The method 'get' was called on null.
Receiver: null
Tried calling: get("score")
这是我对用户数据进行排序的类。
class DatabaseService {
final String uid;
DatabaseService({this.uid});
DocumentSnapshot snapshot;
// Collection reference
final CollectionReference<Map<String, dynamic>> highscoresCollection =
FirebaseFirestore.instance.collection('highscores');
Future updateUserData(String name,int score) async {
return await highscoresCollection.doc(uid).set({
'score': score,
'name': name,
});
}
// high scores list from snapshot
List<HighscoreData> _highscoresListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((doc) {
return HighscoreData(
name: doc.get('name') ?? '', score: doc.get('score') ?? 0);
}).toList();
}
// Get highscores stream
Stream<List<HighscoreData>> get highscores{
return highscoresCollection
.where(('score'), isLessThanOrEqualTo: snapshot.get('score'))
.orderBy('score', descending: true,).limit(5)
.snapshots()
.map(_highscoresListFromSnapshot);
}
UserData _userDataFromSnapshot(DocumentSnapshot snapshot) {
return UserData(
uid: uid,
name: snapshot.get('name'),
score: snapshot.get('score'),
);
}
// Get user document
Stream<UserData> get userData {
return highscoresCollection.doc(uid).snapshots().map(_userDataFromSnapshot);
}
}
感谢您的帮助,如果您需要更多代码,请告诉我!
【问题讨论】:
标签: firebase flutter dart dart-null-safety