首页 > 解决方案 > Flutter/Firestore - 不显示新添加/更改的数据

问题描述

我是 Flutter 的新手,并试图将它与 Firestore 数据库一起使用。我想要做的是,设置一个流来读取某个集合中的文档,然后我将其显示在一个列表中。这显示了一些正确的值。但是当我在 firebase 控制台中添加或更改数据时,这些更改不会显示在我的应用程序中。

我的代码:

class _ListPageState extends State<ListPage> {
  String url;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: StreamBuilder<QuerySnapshot>(
            stream: Firestore.instance.collection('chats').snapshots(),
            builder:
                (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
              if (snapshot.hasError) return Text('Error: ${snapshot.error}');
              switch (snapshot.data) {
                case null:
                  return Container();
                default:
                  return ListView.builder(
                    itemCount: snapshot.data.documents.length,
                    itemBuilder: (context, index) {
                      final item = snapshot.data.documents[index];
                      final itemID = snapshot.data.documents[index].documentID;
                      final list = snapshot.data.documents;
                      print(item['senderName']);

                      return Dismissible(
                        key: Key(itemID),
                        background: Container(color: Colors.red),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: ListTile(
                                title: Text(item['senderName']),
                                onTap: () {
                                  print(itemID);
                                  url = item['senderName'];
                                  _sendDataToSecondScreen(context);
                                },
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  );
              }
            },
          ),
        ),
      ],
    );
  }

  // get the text in the TextField and start the Second Screen
  void _sendDataToSecondScreen(BuildContext context) {
    String textToSend = url;
    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SecondScreen(
            text: textToSend,
          ),
        ));
  }

示例:我最初在我的集合中获得了 3 个文档,每个文档都包含一个值“senderName”。所有这些都在我的应用程序中正确显示。当我进入 Firebase 控制台并手动添加第 4 个文档时,也包含一个值“senderName”,这不会显示在我的应用程序中。我尝试关闭所有内容并重新启动,但没有任何变化。

如果有人知道我在这里做错了什么,我会非常高兴。

更新 - Firebase 中的数据结构

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


推荐阅读