[英]How to get the index of a specific document present in the list of documents retrieved from Firebase Firestore in Flutter?
我正在使用 Flutter 和 Firebase Firestore 構建一個測驗應用程序。 我想在應用程序中顯示當前用戶的排名。 因此,我按照各自分數的降序獲取所有用戶文檔。 現在從這個文檔列表中我想要當前用戶文檔的索引,這也是用戶的等級。
我按照分數的降序排列所有文檔,如下所示:
final Stream<QuerySnapshot> _usersStream = FirebaseFirestore.instance
.collection('users')
.orderBy('totalScore', descending: true)
.snapshots();
現在如何獲取當前用戶文檔的索引出現在所有檢索到的文檔列表中? 我想使用 Streambuilder 來顯示排名。
這是我的 Firestore 數據庫:
更新:
所以我嘗試迭代獲取的文檔以獲取 uid 等於文檔名稱的索引。
首先我定義了一個方法 foorloop()
forloop(
int rank,
var data,
String? uid,
) async {
for (int i = 0; i < data.length; i++) {
if (uid == data[i].toString()) {
rank = i;
}
}
return rank;
}
此方法采用“data”,即從 firestore 中按分數降序獲取的文檔列表,以及“uid”,即當前用戶 uid。 它迭代列表並返回 'rank',這是 uid 等於文檔名稱的索引。
我在文本小部件中調用此方法來顯示排名,但它會顯示一個文本,上面寫着“‘未來’的實例”。 我需要它來顯示預期的索引。 我該如何解決這個問題?
StreamBuilder<QuerySnapshot>(
stream: _usersStream,
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(
color: Colors.deepPurple,
),
);
}
var data = snapshot.data!.docs;
int rank = 0;
return Text(
forloop(rank, data, uid).toString()
);
},
所以我終於明白了。
我定義了一個方法 getRank,它迭代文檔列表並返回索引,其中文檔 ID 等於當前用戶的 uid。 在我在 if 條件中使用 data[i] 而不是 data[i].reference.id 之前,它給出了文檔 ID。
getRank(
int rank,
var data,
String? uid,
) {
for (int i = 0; i < data.length; i++) {
if (uid == data[i].reference.id) {
rank = i + 1;
}
}
return rank;
}
現在我在 Streambuilder 中使用了這個方法
StreamBuilder<QuerySnapshot>(
stream: stream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(
color: Colors.deepPurple,
),
);
}
var data = snapshot.data!.docs;
int rank = 0;
return Text(
getRank(rank, data, uid).toString(),
);
},
);
這里 stream 是:
final Stream<QuerySnapshot> stream = FirebaseFirestore.instance
.collection('users')
.orderBy('totalScore', descending: true)
.snapshots();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.