生成单个排行榜文档而不是获取 Firebase 中的所有用户
Generating a single Leaderboard document instead of fetching through all users in Firebase
目前我的数据库是这样的:
到目前为止,创建排行榜非常简单直接:
我在 initState 中声明我的流:
@override
void initState() {
futureAd = fetchAd();
_mainScoreStream = FirebaseFirestore.instance
.collection('users')
.orderBy('current_score', descending: true)
.where('current_score', isGreaterThan: 0)
.limit(25)
.snapshots();
super.initState();
}
然后在ListView.builder中使用它:
Expanded(
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
DocumentSnapshot data = snapshot.data!.docs[index];
return LeaderboardCard(
currentScore: data['current_score'].toString(),
name: data['name'],
index: index,
isCurrentUser: data.id == user!.uid,
);
},
itemCount: snapshot.data!.docs.length,
),
),
但这使得每个用户在加载排行榜时额外阅读 25 次
我如何创建一个 Firebase 函数来抓取 name
+ current_score
并将其放在一个单独的 leaderboard 文档中,用户可以取而代之因此可以将读数减少到 1 而不是 25,或者在创建排行榜时是否有任何其他方法可以减少读数?
一种方法是创建一个单独的 leaderboard
集合,其中包含带有排行榜数据(用户 ID、姓名、当前分数)的单个文档(或者每个日期一个,如果您关心历史数据),然后使用带有 Firestore Trigger 的函数,该函数在用户文档更新时触发,如果用户的分数更新,则更新排行榜文档。
或者,无论何时更新用户分数,您都可以直接写入用户文档和排行榜文档,并完全跳过该函数。
目前我的数据库是这样的:
到目前为止,创建排行榜非常简单直接:
我在 initState 中声明我的流:
@override
void initState() {
futureAd = fetchAd();
_mainScoreStream = FirebaseFirestore.instance
.collection('users')
.orderBy('current_score', descending: true)
.where('current_score', isGreaterThan: 0)
.limit(25)
.snapshots();
super.initState();
}
然后在ListView.builder中使用它:
Expanded(
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
DocumentSnapshot data = snapshot.data!.docs[index];
return LeaderboardCard(
currentScore: data['current_score'].toString(),
name: data['name'],
index: index,
isCurrentUser: data.id == user!.uid,
);
},
itemCount: snapshot.data!.docs.length,
),
),
但这使得每个用户在加载排行榜时额外阅读 25 次
我如何创建一个 Firebase 函数来抓取 name
+ current_score
并将其放在一个单独的 leaderboard 文档中,用户可以取而代之因此可以将读数减少到 1 而不是 25,或者在创建排行榜时是否有任何其他方法可以减少读数?
一种方法是创建一个单独的 leaderboard
集合,其中包含带有排行榜数据(用户 ID、姓名、当前分数)的单个文档(或者每个日期一个,如果您关心历史数据),然后使用带有 Firestore Trigger 的函数,该函数在用户文档更新时触发,如果用户的分数更新,则更新排行榜文档。
或者,无论何时更新用户分数,您都可以直接写入用户文档和排行榜文档,并完全跳过该函数。