firebase - 即使在导航到其他屏幕后,如何从 Firestore 中获取数据并重复使用它?
问题描述
我想从 firestore 获取数据并使用它在 Flutter 中使用主页上的 ListView 构建卡片。在使用导航菜单在屏幕之间切换时,我打算重用一次在会话中获取的数据,而不是每次返回主页时都从数据库中获取数据。但是,这并没有发生;每次我访问主页时,都会从数据库中获取数据。
FutureBuilder(
future: databaseService(),
builder: (context, snapshot) {
if (snapshot.hasData) {
stringMap = snapshot.data;
}
return ListView.builder(
itemBuilder: (context, index) {
stringMap.forEach((index, value) => {
print("The stringMap is ${stringMap.keys.toList()}"),
});
return HomepageCards(
user: widget.user,
cardDetails: stringMap[stringMap.keys.toList()[index]],
);
},
itemCount: stringMap.length,
scrollDirection: Axis.vertical,
controller: _controller,
shrinkWrap: true,
);
},
)
databaseService() async {
return DatabaseService().streamHomePage(widget.user);
}
数据库服务.dart
class DatabaseService {
final Firestore _db = Firestore.instance;
HomePage home = new HomePage();
Map homePageMap = new Map<String, Map<String, dynamic>>();
/// Query a subcollection
Future streamHomePage(FirebaseUser user) async {
// Initialise the model map
home.homeModel = <String, dynamic>{};
home.homeModel['driverDetails'] = new Map();
var ref = _db
.collection('homepage')
.document(user.uid)
.collection('h')
.document('28032020');
// TODO: Try to use cached data. Also try to find the pattern for switching between server and cache
await ref.get(source: Source.serverAndCache).then((ref) => {
ref.data.forEach((index, value) => {
home.homeModel = value,
homePageMap[index] = value,
}),
});
return homePageMap;
}
}
任何使获取的数据可重复使用的线索都将受到高度赞赏。
解决方案
由于您只想获取一次然后从会话中获取它,因此您可以检查会话是否包含数据。另一种方法是使用shared_preferences
,例如:
SharedPreferences prefs = await SharedPreferences.getInstance();
databaseService() async {
await prefs.setBool('retrieved', true);
return DatabaseService().streamHomePage(widget.user);
}
然后在执行FutureBuilder
检查是否检索到等于 true 之前使用getBool()
并从会话中检索数据
推荐阅读
- excel - 如何使用另存为功能?
- php - Output data with php to csv not inbetween quotes but straight [field]=data
- html - 语义 HTML – 如何呈现产品比较?
- c# - 用户选择的路径
- weblogic - 如何在不硬编码集群名称或在属性文件中指定集群名称的情况下将 WorkManager 定位到多个集群
- java - 无法启动接收器 com.google.android.gms.gcm.GcmReceiver
- xamarin - Xamarin MessagingCenter 不适用于某些页面
- css - CSS 环绕内容流
- javascript - 如何使用任何高阶运算符保留中间数据?
- c# - 我无法获取个人资料页面视图的授权帐户 ID(主键)