【问题标题】:Flutter: Pre-load data into Firestore local cache on the first loadFlutter:在第一次加载时将数据预加载到 Firestore 本地缓存中
【发布时间】:2018-09-20 00:37:51
【问题描述】:

我在我的 Flutter 应用中实现了 Cloud Firestore,但遇到了这个问题:如果在第一次加载应用时(安装后)没有网络连接,则不会显示任何数据。 我的问题是:如何使 Firestore 中的数据即使在没有互联网连接的情况下也能在首次加载(安装后)时显示?我获取数据的代码是这样的:

class QuestionsListState extends State<QuestionsList> {
  @override
  Widget build(BuildContext context) {

    return new StreamBuilder<QuerySnapshot>(
      stream: _questionsCollectionReference
          .where("category", isEqualTo: _chosenCategory).orderBy("order").snapshots,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) return const Text('');
        final int messageCount = snapshot.data.documents.length;
        return new ListView.builder(
          itemCount: messageCount,
          itemBuilder: (_, int index) {
            final DocumentSnapshot document = snapshot.data.documents[index];
            return new ListTile(
              title: new FlatButton(
                  onPressed: () {
                    Navigator.push(context, new MaterialPageRoute(
                      builder: (BuildContext context) => new AddAnswerDialog(),
                      fullscreenDialog: true,
                    ));
                  },
                  child: new Text(
                    document['text'],
                    style: new TextStyle(fontSize: 18.0, color: Colors.blue),
                  )),
            );
          },
        );
      },
    );
  }
}

【问题讨论】:

    标签: dart google-cloud-firestore flutter preload offline-caching


    【解决方案1】:

    我遇到了类似的情况。我的解决方案是从磁盘加载数据,使用FutureBuilder 而不是const Text('')

    换句话说,你的结构是:

    • 流生成器
      • hasData 为假时
        • 未来建设者
          • hasData 为假时
            • 显示CircularProgress
          • hasData 为真时
            • 显示磁盘数据
      • hasData 为真时
        • 显示在线数据

    对于初次使用的用户,这将显示CircularProgress,然后是磁盘中的数据,然后是在线数据。如果在线数据没有加载(没有网络),用户一直看到磁盘数据。

    【讨论】:

      【解决方案2】:

      可以在再次添加之前检查是否已经缓存了任何数据。

      还发现 Tensor Programming 的这个颤振信息 YouTube 视频很有用 Making Use of Utility Plugins for Dart's Flutter Framework 尤其是连接状态部分。

      【讨论】:

        【解决方案3】:

        这样可以吗?尚未尝试,但正在考虑下个月为最初的离线国家公园应用程序做类似的事情。

        Firestore.instance.collection('<collection>').document().setData(
                {
                  '<field>': '<data>',
                },
              );
        

        使用 Cloud Firestore 插件 > https://github.com/flutter/plugins/tree/master/packages/cloud_firestore

        【讨论】:

        • 是的,但我只需要执行一次 - 在安装后的第一次加载时。所以我会考虑将代码放在正确的位置或尝试将缓存与应用程序文件一起放在 apk 中。谢谢!
        • 我真的不明白它与这个问题有什么关系
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        • 2018-11-17
        • 2020-09-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多