Search code examples
firebaseflutterdartgoogle-cloud-firestorechat

Flutter-Firebase File View/Download between peers


I am working on a chatting app using Flutter & Firebase. One feature i wanted to include is been able to send files which I eventually figured out after some research. But there is something I really want included. For instance I send an image to another user, in the users device, he should manually have to download it before he can see the image and then on my own device, after I'm done sending that image, I should be able to just view the image directly without having to download the image again myself. Would be really grateful if I can get assistance on this.


Solution

  • I will give a brief idea of my take on this implementation.

    So,

    • Data Model for the chat messages

    Hope you have a proper DataModel for your chat messages. What I would suggest is, you have a data model similar to this

    class ChatMessage{
      String uid; 
      String message;
      String imageUrl;  //List<String> imageUrl depending on your use case 
    ...
    }
    
    • Structuring your backend

    Make sure your Firebase Collections are well Structured, Would recommend having a single connection, Called Chats, And document with an id and subcollection with all the messages of that chat, this way you only have to listen to that particular collection. But you could refer to other implementations on youtube as well.

    • Letting user download

    What you need here is, the package:flutter_blurhash With this you can modify your chat message to include a Hash property.

    class ChatMessage{
      String id; 
      String message;
      String imageUrl;  //List<String> imageUrl depending on your use case
      String hash; 
    ...
    }
    

    Using this, now you can store a hash of an image in the database and send that to show on the peer's side. This will show only a blurred version of the image, use a Stack and add an IconButton() with a download Icon. Now when clicked on it you can implement to get the download imageUrl and then display that instead of the the Hash.

    You can now store this image in the localStorage and then fetch from that location just like WhatsApp does it. You can do the same on the sender's side as well. This way you will be saving a lot of Bandwdith of fetching images from firebase all the time.

    • Bottomline

    Use BlurHash() to show a blurred Image, Download it and cache it on clicked. show image on both the side by from the cached location.