本文介绍了如何在Streambuilder中查询Firestore文档并更新ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从名为帖子的Firestore集合检索帖子,其中包含帖子创建者的用户ID 和帖子说明,并且可以通过同时使用StreamBuilder和FutureBuilder来实现(不建议,因为它只会获取一次快照,并且在字段更改时不会更新)。

I'm trying to retrieve posts from a Firestore collection called "posts", which contains the post creator's userID and post description and this is possible by using both StreamBuilder and FutureBuilder(Not preferable, because it gets a snapshot only once and doesn't update when a field changes).

但是,我想用发布创建者的用户ID 查询另一个名为用户的集合,并检索与userId匹配的文档。

However, I want to query another collection called "users" with the post creator's userID and retrieve the document that matches the userId.

这是我的第一种方法:

StreamBuilder<QuerySnapshot>(
  stream:Firestore.instance.collection("posts").snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) {
      return Center(
        child: _showProgressBar,
      );
    }

   List<DocumentSnapshot> reversedDocuments = snapshot.data.documents.reversed.toList();
    return ListView.builder(
      itemCount: reversedDocuments.length,
      itemBuilder: (BuildContext context, int index){

        String postAuthorID = reversedDocuments[index].data["postAuthorID"].toString();
        String postAuthorName = '';
        Firestore.instance.collection("users")
        .where("userID", isEqualTo: postAuthorID).snapshots().listen((dataSnapshot) {
            print(postAuthorName = dataSnapshot.documents[0].data["username"]);
          setState(() {
            postAuthorName = dataSnapshot.documents[0].data["username"];
          });
        });

        String desc = reversedDocuments[index].data["post_desc"].toString();

        return new ListTile(
          title: Container(
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Card(
                    child: new Column(
                      children: <Widget>[
                        ListTile(
                          title: Text(postAuthorName, //Here, the value is not changed, it holds empty space.
                            style: TextStyle(
                              fontSize: 20.0,
                            ),
                          ),
                          subtitle: Text(desc),
                        ),
                       )

了解到ListView.builder()只能根据DocumentSnapshot列表呈现项目

After understanding that ListView.builder() can only render items based on the DocumentSnapshot list and can't handle queries inside the builder.

经过大量研究:
I tri例如,尝试在initState()中构建列表,尝试使用嵌套流生成器:

After many research:I tried many alternatives like, trying to build the list in the initState(), tried using the Nested Stream Builder:

return StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance.collection('posts').snapshots(),
  builder: (context, snapshot1){
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection("users").snapshots(),
      builder: (context, snapshot2){
        return ListView.builder(
          itemCount: snapshot1.data.documents.length,
          itemBuilder: (context, index){
            String desc = snapshot1.data.documents[index].data['post_description'].toString();
            String taskAuthorID = snapshot1.data.documents[index].data['post_authorID'].toString();
            var usersMap = snapshot2.data.documents.asMap();
            String authorName;
            username.forEach((len, snap){
              print("Position: $len, Data: ${snap.data["username"]}");
              if(snap.documentID == post_AuthorID){
                authorName = snap.data["username"].toString();
              }
            });
            return ListTile(
              title: Text(desc),
              subtitle: Text(authorName), //Crashes here...
            );
          },
        );
      }
    );
  }
);

尝试与Stream Group并找不到解决方法,因为它只是结合了两个流,但我希望第二个流由第一个流中的值获取。

Tried with Stream Group and couldn't figure out a way to get this done, since it just combines two streams, but I want the second stream to be fetched by a value from first stream.

这是我的Firebase集合屏幕截图:

This is my Firebase Collection screenshot:

Firestore帖子集合:

Firestore "posts" collection:

Firestore用户集合:

Firestore "users" collection:

我知道这是一件非常简单的事情,但仍然找不到任何教程或文章来实现。

I know this is a very simple thing, but still couldn't find any tutorial or articles to achieve this.

推荐答案

我发布了一个类似的问题,后来找到了一个解决方案:将itemBuilder返回的小部件设置为有状态,并在其中使用FutureBuilder。

I posted a similar question and later found a solution: make the widget returned by the itemBuilder stateful and use a FutureBuilder in it.

这是我的代码。对于您的情况,您想使用一个新的有状态小部件而不是ListTile,因此可以添加FutureBuilder来调用异步函数。

Here's my code. In your case, your would want to use a new Stateful widget instead of ListTile, so you can add the FutureBuilder to call an async function.

StreamBuilder(
                  stream: Firestore.instance
                      .collection("messages").snapshots(),
                  builder: (context, snapshot) {
                    switch (snapshot.connectionState) {
                      case ConnectionState.none:
                      case ConnectionState.waiting:
                        return Center(
                          child: PlatformProgressIndicator(),
                        );
                      default:
                        return ListView.builder(
                          reverse: true,
                          itemCount: snapshot.data.documents.length,
                          itemBuilder: (context, index) {
                            List rev = snapshot.data.documents.reversed.toList();
                            ChatMessageModel message = ChatMessageModel.fromSnapshot(rev[index]);
                            return ChatMessage(message);
                          },
                        );
                    }
                  },
                )


class ChatMessage extends StatefulWidget {
  final ChatMessageModel _message;
  ChatMessage(this._message);
  @override
  _ChatMessageState createState() => _ChatMessageState(_message);
}

class _ChatMessageState extends State<ChatMessage> {
  final ChatMessageModel _message;

  _ChatMessageState(this._message);

  Future<ChatMessageModel> _load() async {
    await _message.loadUser();
    return _message;
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
      child: FutureBuilder(
        future: _load(),
        builder: (context, AsyncSnapshot<ChatMessageModel>message) {
          if (!message.hasData)
            return Container();
          return Row(
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(right: 16.0),
                child: GestureDetector(
                  child: CircleAvatar(
                    backgroundImage: NetworkImage(message.data.user.pictureUrl),
                  ),
                  onTap: () {
                    Navigator.of(context)
                        .push(MaterialPageRoute(builder: (context) =>
                        ProfileScreen(message.data.user)));
                  },
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      message.data.user.name,
                      style: Theme.of(context).textTheme.subhead,
                    ),
                    Container(
                        margin: const EdgeInsets.only(top: 5.0),
                        child: _message.mediaUrl != null
                            ? Image.network(_message.mediaUrl, width: 250.0)
                            : Text(_message.text))
                  ],
                ),
              )
            ],
          );
        },
      ),
    );
  }
}
class ChatMessageModel {
  String id;
  String userId;
  String text;
  String mediaUrl;
  int createdAt;
  String replyId;
  UserModel user;

  ChatMessageModel({String text, String mediaUrl, String userId}) {
    this.text = text;
    this.mediaUrl = mediaUrl;
    this.userId = userId;
  }

  ChatMessageModel.fromSnapshot(DocumentSnapshot snapshot) {
    this.id = snapshot.documentID;
    this.text = snapshot.data["text"];
    this.mediaUrl = snapshot.data["mediaUrl"];
    this.createdAt = snapshot.data["createdAt"];
    this.replyId = snapshot.data["replyId"];
    this.userId = snapshot.data["userId"];
  }

  Map toMap() {
    Map<String, dynamic> map = {
      "text": this.text,
      "mediaUrl": this.mediaUrl,
      "userId": this.userId,
      "createdAt": this.createdAt
    };
    return map;

  }

  Future<void> loadUser() async {
    DocumentSnapshot ds = await Firestore.instance
        .collection("users").document(this.userId).get();
    if (ds != null)
      this.user = UserModel.fromSnapshot(ds);
  }

}

这篇关于如何在Streambuilder中查询Firestore文档并更新ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 16:45