Flutter 如何优化 Firestore 存储读取以防止大量不必要的读取



我正在构建一个 当用户登录到应用程序时,它会显示所有用户的信息,这些信息也在应用程序上注册。使用我的 init fetch 方法获取所有信息,它使用大量读取,从几天的测试中读取了 1.3k,而只有 4 个用户注册。这是异常高的。

我的获取方法,从火堆获取用户信息

void loadUserProfiles() async {
var firebaseUser = await FirebaseAuth.instance.currentUser();
List<String> tempUsers = List<String>();
List<String> tempNames = List<String>();
List<String> tempImages = List<String>();
imageUrl.clear();
names.clear();
userId.clear();
tempUsers.clear();
tempNames.clear();
tempImages.clear();
setState(() {
isLoading = true; //Data is loading
});
// Adds all the values of each user from firestore to their list to compare
await firestoreInstance
.collection("users")
.getDocuments()
.then((QuerySnapshot snapshot) async {
snapshot.documents.forEach((f) async {
if (f.documentID != firebaseUser.uid) {
tempUsers.add(f.data['userid']);
tempNames.add(f.data['name']);
tempImages.add(f.data['images'][0]);
}
});
});
// Adds user to list to load to user cards if doesnt exist in liked users firestore
for (int i = 0; i < tempUsers.length; i++) {
await firestoreInstance
.collection("users")
.document(firebaseUser.uid)
.collection("liked_users")
.document(tempUsers[i])
.get()
.then((value) async {
if (!value.exists) {
userId.add(tempUsers[i]);
names.add(tempNames[i]);
imageUrl.add(tempImages[i]);
}
});
}
setState(() {
isLoading = false; //Data has loaded
});
}

我这样做的方法是它获取所有数据并将它们存储到三个单独的临时列表中。然后使用这些列表,我会再次通读 firestore 以比较当前用户喜欢的用户 ID 是否存在于集合中。

情况也变得更糟,因为我使用底部导航栏,每当单击该页面时,它都会再次启动我的加载方法,该方法使用更多读取。

您可以执行以下几项操作:

  1. 分页 在您的代码getDocuments中,您似乎正在检索每个用户。一般来说,对于庞大的馆藏(通常是为了提供列表(,我们尝试只获取那些将要出现在视野中的文档,比如说前 20 个文档。一旦达到最大滚动范围,我们就会获取下一个 20。

  2. 对于您的重新加载问题,请尝试使用initState函数进行获取。将其放置在某个位置,以便它仅在需要时运行。我不知道您的应用程序结构,但让我们在我的应用程序中说。我已经将所有通常不会更改的基本数据的初始检索放在我的初始登录逻辑中,而不是每次我们路由到需要数据的页面时都这样做

  3. 此外,谷歌还有一个官方指南,比如Cursors.检查一下,看看其他解决方案是否更合适。

最新更新