How to create Foreign key in firebase for chat app

Viewed 55

I create chat app applicattion have many conversation which i can have conversation, my problem depend on receive messages by another account. most work correctly but when i loggin to another user i receive the same messages as in the previous one user which didn't conduct a conversation. i suppose i need foregin key

Column(children: 
[
StreamBuilder(
 //currentLoggedUserId - user which is logged right now
  stream:FirebaseFirestore.instance.collection('users').doc(currentLoggedUserId).snapshots(),
  builder: (BuildContext context, AsyncSnapshot snapshot)
{
 
 return Center(child:
 
ListView.builder(
  shrinkWrap:true,
                 itemCount: snapshot.data['messages'].length,
                  itemBuilder: (BuildContext context, int index){
                   
                    return  ChatBubble(
        clipper: ChatBubbleClipper1(type: BubbleType.sendBubble),
        alignment: Alignment.topRight,
        margin: EdgeInsets.only(top: 20),
        backGroundColor: Colors.blue,
        child: Container(
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width * 0.7,
          ),
          child: Text(
            snapshot.data['messages'][index],
            style: TextStyle(color: Colors.white),
          ),
        ),
      );
    },),
 );
}),

StreamBuilder(
  //writer is DocumentId  account which i have conversation 
  stream:FirebaseFirestore.instance.collection('users').doc(writer).snapshots(),
  builder: (BuildContext context, AsyncSnapshot snapshot)
{

 return Center(child:
 
ListView.builder(
  shrinkWrap:true,
                  itemCount: snapshot.data['messages']?.length ,
                  itemBuilder: (BuildContext context, int index){
                   
                    return    
                    
                     ChatBubble(
    clipper: ChatBubbleClipper1(type: BubbleType.receiverBubble),
    backGroundColor: Color(0xffE7E7ED),
    margin: EdgeInsets.only(top: 20),
    child: Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width * 0.7,
      ),
      child: Text(
        snapshot.data['messages'][index],
        style: TextStyle(color: Colors.black),
        
      ),),);},),);}),],)
1 Answers

So one important thing to note is that Firebase "tables" aren't really like your RDBMS tables where you can have primary and foreign keys. You need to manage that manually. Simply store the ID of your primary key in every document that you create which you want to have a reference to the other "table".

Related