Home > Software engineering >  How to use function inside stream builder for fetching user detail based on userid in flutter?
How to use function inside stream builder for fetching user detail based on userid in flutter?

Time:09-01

enter image description here

As a learning purpose I have created a simple app for chatrooms, using firebase

In cloud firestore i have two collections named users and chatrooms

Users collection containing all fields about userdetails like full name, email

and chatroom contains chatroomid,lastmessage,lastmessagetime and participants(two chat users) with their id

Now I want to print all chatroom as a list tile with the full name of chatroom participants,

but here I confuse how to fetch full name which is stored in other collection named users.

I am thinking for creating a function that pass id and get full name from users collection but how to use and where to use...

this is a just a demo to explain what I want to do...

I have many things regarding such join with two collections...

if I get it solved..I will solve others my own...

Thanks..

StreamBuilder(
            stream: FirebaseFirestore.instance
                .collection("chatrooms").
                snapshots(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.active) {
                if (snapshot.hasData) {
                  QuerySnapshot querysnapshot = snapshot.data as QuerySnapshot;
                  return ListView.builder(
                      itemCount: querysnapshot.docs.length,
                      itemBuilder: (context, index) {
                        ChatRoomModel chatroommodel = ChatRoomModel.fromMap(
                            querysnapshot.docs[index].data()
                            as Map<String, dynamic>);
                         return ListTile(

//can I use a function here for fetching user data?
                           title:Text(getfullname(chatroommodel.participants!.keys.first)),
                           subtitle: Text(getfullname(chatroommodel.participants!.keys.last)),
                           leading: CircleAvatar());
                      });
                } else {
                return Text('Something wrong');
                }
              } else {
                return Center(
                  child: CircularProgressIndicator(),
                );
              }
            },
          )

ChatRoomModel

class ChatRoomModel {
  String? chatroomid;
  Map<String, dynamic>? participants;
  String? lastMessage;
  DateTime? lastmessagetime;

  ChatRoomModel({this.chatroomid, this.participants, this.lastMessage,this.lastmessagetime});

  ChatRoomModel.fromMap(Map<String, dynamic> map) {
    chatroomid = map["chatroomid"];
    participants = map["participants"];
    lastMessage = map["lastmessage"];
    lastmessagetime = map["lastmessagetime"].toDate();
  }

  Map<String, dynamic> toMap() {
    return {
      "chatroomid": chatroomid,
      "participants": participants,
      "lastmessage": lastMessage,
      "lastmessagetime":lastmessagetime,
    };
  }
}

user model

class UserModel {
  String? uid;
  String? fullname;
  String? imageurl;
  String? email;
  String? onlinestatus;

  UserModel(
      {required this.uid,
      required this.email,
      required this.imageurl,
      required this.fullname,
      this.onlinestatus='false'});

  Map<String, dynamic> tomap() {
    return {
      'uid': uid,
      'fullname': fullname,
      'imageurl': imageurl,
      'email': email,
      'onlinestatus':onlinestatus,
    };
  }

  UserModel.fromjson(Map<String, dynamic> map) {
    uid = map['uid'];
    fullname = map['fullname'];
    imageurl = map['imageurl'];
    email = map['email'];
    onlinestatus=map['onlinestatus'];
  }
}

CodePudding user response:

As mentioned in a similar Stackoverflow case :

Firestore doesn't support foreign keys like SQL databases, so you can't retrieve nested data like SQL. Firestore is a no-SQL database that doesn't have any notion of reference. The only thing Firestore understands are key-values, documents and collections, everything else has to be modeled on top of that. See Firestore data model.

In Firestore you need to fetch referenced data separately, either you can fetch all users data separately in parallel with orders data and store it in map, or if you don't need users data initially then fetch each users data when needed like when you check details of each order.

You can refer to this Stackoverflow link for more details.

  • Related