首页 > 解决方案 > 即使在导航到其他屏幕后,如何从 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;
  }
}

任何使获取的数据可重复使用的线索都将受到高度赞赏。

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


由于您只想获取一次然后从会话中获取它,因此您可以检查会话是否包含数据。另一种方法是使用shared_preferences,例如:

  SharedPreferences prefs = await SharedPreferences.getInstance();

  databaseService() async {
     await prefs.setBool('retrieved', true);
    return DatabaseService().streamHomePage(widget.user);
  }

然后在执行FutureBuilder检查是否检索到等于 true 之前使用getBool()并从会话中检索数据


推荐阅读