Ayrix
Ayrix

Reputation: 491

How to use StreamBuilder in FirebaseStorage to inform my App from changes in my Firebase Storage? In Flutter

Here is my challenge:

I'm using the following example from https://firebase.flutter.dev/docs/storage/usage/ to upload images to my FireBaseStorage from my phone gallery (which delivers me the String filepath-variable).

    Future<void> handleTaskExample2(String filePath) async {
      File largeFile = File(filePath);
    
      firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
          .ref('uploads/picture-to-upload.jpeg')
          .putFile(largeFile);
    
      task.snapshotEvents.listen((firebase_storage.TaskSnapshot snapshot) {
        print('Task state: ${snapshot.state}');
        print(
            'Progress: ${(snapshot.bytesTransferred / snapshot.totalBytes) * 100} %');
      }, onError: (e) {
        print(task.snapshot);
        if (e.code == 'permission-denied') {
          print('User does not have permission to upload to this reference.');
        }
      });
      try {
        await task;
        print('Upload complete.');
      } on firebase_core.FirebaseException catch (e) {
        if (e.code == 'permission-denied') {
          print('User does not have permission to upload to this reference.');
        }
        // ...
      }
    }

Actually, everything works fine. My uploaded Image to my Storage gets shown in my GridView inside the App...

But if I upload an Image to my Storage manually over the FireBase Website, my gridView (where the pictures from my storage are shown) is not auto-updating.

But if I change my screen and come back, the manually uploaded picture is shown.

It looks like I need something like a StreamBuilder that my App gets informed whenever changes happen in my Storage.

Does anyone have an Idea how to implement this or any other ideas to solve my problem?

Thanks

Upvotes: 0

Views: 310

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7388

The listAll and list only get the data once so you unfortunately can't have a stream on them. You have 2 options here.

  1. Call the listAll in a periodic interval like every 2-3 min
  2. Create a cloud functions that get's triggered when files get uploaded to that specific directory and change a value in RTDB or Firestore. In the App you can listen to that data. Idealy it should be just a timestamp. You can store in your app the last timestamp you got from the database and if that changes just call listAll.

It depends on your usecase what would fit for you the best.

Upvotes: 1

Related Questions