Search code examples
firebaseflutterdartcachingfirebase-storage

How to store Firebase Storage Items to local cache to save bandwidth costs?


I'm enrolled in a project using Flutter and Firebase and I'm having trouble with bandwidth limits. The free quota is 1gb per day and I have a list with 100 images (and some files).

Is there a way to minimize the bandwidth costs through caching this files in local phone cache to not have to get the items from DB each time I open the screen?

Is there a package or something like this to do it?


Solution

  • You can use CachedNetworkImage package to avoid downloading the image every time. It's simple to use and you just need to pass the URL to the Widget:

    CachedNetworkImage(
            imageUrl: "http://via.placeholder.com/350x150",
            placeholder: (context, url) => CircularProgressIndicator(),
            errorWidget: (context, url, error) => Icon(Icons.error),
         ),
    

    To control how long the image is cached*, make sure you add cache header to your images when you upload them so they get cached properly (in the browser too if you're using flutter web):

        final contentType = 'image/*'; 
        final cacheControl = 'public, max-age=31556926'; // seconds -- ie 31556926 == one year
        final uploadTask = reference.putData(
            image.data,
            SettableMetadata(
              cacheControl: cacheControl,
              contentType: contentType,
            ));
    
    

    So make sure to store the URL of the images when you upload them and just pass the URL to the users to get the images instead of downloading the images directly from FirebaseStorage in case you're doing that.

    *I believe the package default is 7 days if no cache header is available but I cannot confirm.