如果不刷新页面,我看不到从 Firestore 提取的数据


List<String> docGameInfoId = [];

getGamesId() async {
await FirebaseFirestore.instance
.collection('gameinfo')
.get()
.then((snapshot) {
docGameInfoId = [];
for (var element in snapshot.docs) {
docGameInfoId.add(element.reference.id);
}
});
}

这是我使用gameinfo集合的代码。

FutureBuilder(
future: getGamesId(),
builder: (context, snapshot) {
return ListView.builder(
itemCount: docGameInfoId.length,
itemBuilder: (context, index) {
return Container(
height: 300,
child: GetGamesInfo(documentId: docGameInfoId[index]),
);
},
);
},
),

下面是我在列表中显示从Firestore主页上获得的selectedGame数据的代码

final String documentId;
CollectionReference users =
FirebaseFirestore.instance.collection('gameinfo');
return FutureBuilder<DocumentSnapshot>(
future: users.doc(documentId).get(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data =
snapshot.data!.data() as Map<String, dynamic>;
return Center(child: Center(child: Text('${data['selectedGame']}')));
}
return const Text('');
},
);

我的<<p> strong> GetGamesId 文档。我能够正确地保存数据,并在我的主页上显示它没有问题。但我无法看到我添加的最后数据,除非我刷新页面或转到另一个页面并返回主页面。我还可以看到页面刷新时最后添加的数据。

您可以将Streambuilder与Firebase的.snapshots()方法一起使用。否则,您将只能在调用.get()时从数据库中获得当前值,使用.snapshots()时,您将侦听任何更改。

这里有更多信息