Flutter:首次加载时将数据预加载到 Firestore 本地缓存中

Dar*_*han 6 preload offline-caching dart flutter google-cloud-firestore

我已经在我的 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),
                  )),
            );
          },
        );
      },
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

And*_*onu 4

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

换句话说,你的结构将是:

  • 流生成器
    • 什么时候hasData为假
      • 未来建造者
        • 什么时候hasData为假
          • 显示一个CircularProgress
        • 什么时候hasData是真的
          • 显示磁盘数据
    • 什么时候hasData是真的
      • 显示在线数据

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