【问题标题】:Flutter: Get Document SnapshotFlutter:获取文档快照
【发布时间】:2019-03-22 17:34:31
【问题描述】:

我创建了一个 Listview 构建器,将 buildChatList 作为我的 itembuilder 传递,但我注意到当我热重启或重建应用程序时,buildChatList 没有返回任何内容,但当我热重加载时实际上返回了预期的数据。 我不明白为什么会这样。我需要帮助。

以下是我目前的代码。

buildChatList(BuildContext context, int index) {
    Map<String, dynamic> userDocumentt;
    print('INDEX $index COUNT $currentUserActiveChatsLength');
    String thisUserID = currentUserActiveChats[index];
    if (user.uid.hashCode <= thisUserID.hashCode) {
      groupChatId = '$_cuserID-$thisUserID';
    } else {
      groupChatId = '$thisUserID-$_cuserID';
    }
    Stream<QuerySnapshot> unreadMessages = Firestore.instance
        .collection('messages')
        .where("chatDetails.to", isEqualTo: user.uid)
        .where("chatDetails.sender", isEqualTo: thisUserID)
        .where("chatDetails.hasRead", isEqualTo: false)
        .snapshots();
    unreadMessages.listen((QuerySnapshot data) {
      unReadMessageLength = data.documents.length;
    });

    Stream<QuerySnapshot> lastMess = Firestore.instance
        .collection('messages')
        .where('groupChatId', isEqualTo: groupChatId)
        .orderBy('chatDetails.timestamp', descending: true)
        .limit(1)
        .snapshots();
    lastMess.listen((QuerySnapshot data) {
      List<DocumentSnapshot> userLastMess = data.documents;
      chatDetailSnapshotList = userLastMess.map((DocumentSnapshot doc) {
        return doc.data;
      }).toList();
    });
    Stream<DocumentSnapshot> userP = usersRef.document(thisUserID).snapshots();
    userP.listen((DocumentSnapshot snap) {
      userDocumentt = Map.from(snap.data);
      if (userDocumentt != null) {
        print('HELLOo $userDocumentt');
        myResult = new InkWell(
          highlightColor: Colors.grey[300],
          onTap: () {
            Navigator.of(context, rootNavigator: true).push(
                new MaterialPageRoute(
                    builder: (context) =>
                        new Chat(chatWith: userDocumentt['id'])));
          },
          onLongPress: () {
            setState(() {
              modifyMode = true;
            });
          },
          child: new Container(
            margin: EdgeInsets.only(left: 15.0, right: 15.0),
            child: new Column(
              children: <Widget>[
                new Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[

                    new Expanded(
                      child: new Container(
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(
                              margin: EdgeInsets.only(left: 17.0, top: 5.0),
                              child: new Text(
                                userDocumentt['username'],
                                style: new TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16.0,
                                ),
                              ),
                            ),
                            new Container(
                              margin: EdgeInsets.only(left: 17.0, top: 7.0),
                              child: new Text(
                                chatDetailSnapshotList[0]["chatDetails"]
                                    ["content"],
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: new TextStyle(
                                  fontSize: 15.0,
                                  color: Colors.grey[800],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                new Container(
                  margin: EdgeInsets.only(left: 72.0, top: 6.0, bottom: 6.0),
                  child: new Divider(
                    color: Colors.grey[300],
                    height: 10.0,
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        print('HELLLLOOO $userDocumentt');
        myResult = CircularProgressIndicator();
      }
    });
    return myResult;
  }

【问题讨论】:

  • 您是否在 build() 方法中获取数据(使用流)?那是行不通的。您应该在 initState() 方法中设置所有侦听器,并在它们触发时使用 setState() 更新内部组件状态,然后重建 UI。

标签: dart nosql flutter google-cloud-firestore


【解决方案1】:

对于 Firestore 使用 'StreamBuilder' 进行实时更新是有意义的,我给你一个我拥有的示例代码,希望它有所帮助。

StreamBuilder(
                 stream: Firestore.instance.collection("YourCollectionNAme").snapshots(),
                 builder: (BuildContext  context,AsyncSnapshot snapshot)
                 {
                   if (snapshot.hasData)
                   {
                   return new ListView.builder(
                     shrinkWrap: true,
                     itemCount: snapshot.data.documents.length,
                     padding: const EdgeInsets.only(top: 5.0),
                     itemBuilder: (context, index) {
                      DocumentSnapshot ds = snapshot.data.documents[index];
                      return new Row(
                        textDirection: TextDirection.ltr,
                          children: <Widget>[
                            Expanded (child:Text(ds["Field-of-collection"]) ),
                            Expanded (child:Text(ds["another-field"]) ),
                            Expanded (child:Text(ds["last-field"].toString()) ),


                          ],
                      );
      }
                   );
                 }
                 },
               )

我正在为我的 Firestore 集合使用列表视图。

【讨论】:

  • 这确实很好用,但是当我必须获取基于 uid 的文档时会发生什么,但我还没有准备好?我需要加载正在使用该应用程序的用户的文档,因此身份验证需要一些时间,直到我可以得到这个uids
  • 您是否尝试在应用中的任何内容之前使用身份验证或登录页面?
  • 不,但因为我不需要它。用户将登录...或不登录。如果他不想,我需要等到他先登录才能得到他的uid
  • 在这种情况下,使用条件,例如如果 uid 存在,则加载 x 东西
【解决方案2】:

您将需要使用StreamBuilder 而不是普通的 ListView.builder()。 检查这个link

更新数据并不意味着更新您需要在添加的每条新记录上重建此小部件的视图,因此当您热重加载应用程序时,您手动运行 setState() 以显示更新。

StreamBuilder 将为您在每条新记录上执行此 setState()

【讨论】:

    【解决方案3】:

    我猜你没有返回流试试这个。

    buildChatList(BuildContext context, int index) {
    Map<String, dynamic> userDocumentt;
    print('INDEX $index COUNT $currentUserActiveChatsLength');
    String thisUserID = currentUserActiveChats[index];
    if (user.uid.hashCode <= thisUserID.hashCode) {
      groupChatId = '$_cuserID-$thisUserID';
    } else {
      groupChatId = '$thisUserID-$_cuserID';
    }
    Stream<QuerySnapshot> unreadMessages = Firestore.instance
        .collection('messages')
        .where("chatDetails.to", isEqualTo: user.uid)
        .where("chatDetails.sender", isEqualTo: thisUserID)
        .where("chatDetails.hasRead", isEqualTo: false)
        .snapshots();
    unreadMessages.listen((QuerySnapshot data) {
      unReadMessageLength = data.documents.length;
    });
    
    Stream<QuerySnapshot> lastMess = Firestore.instance
        .collection('messages')
        .where('groupChatId', isEqualTo: groupChatId)
        .orderBy('chatDetails.timestamp', descending: true)
        .limit(1)
        .snapshots();
    lastMess.listen((QuerySnapshot data) {
      List<DocumentSnapshot> userLastMess = data.documents;
      chatDetailSnapshotList = userLastMess.map((DocumentSnapshot doc) {
        return doc.data;
      }).toList();
    });
    myResult = Stream<DocumentSnapshot> userP = usersRef.document(thisUserID).snapshots();
    userP.listen((DocumentSnapshot snap) {
      userDocumentt = Map.from(snap.data);
      if (userDocumentt != null) {
        print('HELLOo $userDocumentt');
        return InkWell(
          highlightColor: Colors.grey[300],
          onTap: () {
            Navigator.of(context, rootNavigator: true).push(
                new MaterialPageRoute(
                    builder: (context) =>
                        new Chat(chatWith: userDocumentt['id'])));
          },
          onLongPress: () {
            setState(() {
              modifyMode = true;
            });
          },
          child: new Container(
            margin: EdgeInsets.only(left: 15.0, right: 15.0),
            child: new Column(
              children: <Widget>[
                new Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    new Expanded(
                      child: new Container(
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(
                              margin: EdgeInsets.only(left: 17.0, top: 5.0),
                              child: new Text(
                                userDocumentt['username'],
                                style: new TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16.0,
                                ),
                              ),
                            ),
                            new Container(
                              margin: EdgeInsets.only(left: 17.0, top: 7.0),
                              child: new Text(
                                chatDetailSnapshotList[0]["chatDetails"]
                                    ["content"],
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: new TextStyle(
                                  fontSize: 15.0,
                                  color: Colors.grey[800],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                new Container(
                  margin: EdgeInsets.only(left: 72.0, top: 6.0, bottom: 6.0),
                  child: new Divider(
                    color: Colors.grey[300],
                    height: 10.0,
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
    
        //
        print('HELLLLOOO $userDocumentt');
        myResult = CircularProgressIndicator();
      }
    });
    return myResult;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-25
      • 2021-04-21
      • 2018-03-19
      • 2020-11-27
      • 2020-12-16
      • 2023-03-19
      • 1970-01-01
      • 2019-08-02
      相关资源
      最近更新 更多