0
votes

I'm uploading multiple images to Cloud Storage, I've read I can tap into the stream to display an upload progress bar however I can't see a way to do this.

  Future<dynamic> postImage(Asset imageFile) async {
    String fileName = DateTime.now().toString();
    StorageReference reference = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask _uploadTask =
        reference.putData((await imageFile.getByteData()).buffer.asUint8List());
    StorageTaskSnapshot storageTaskSnapshot = await _uploadTask.onComplete;
    return storageTaskSnapshot.ref.getDownloadURL();
  }
1

1 Answers

0
votes

There's an example of how to use the firebase-storage plugin in the FlutterFire repo, that is pretty handy.

That example pretty much performs calls on the StorageUploadTask task that you have, to determine the upload state and progress.

  String get status {
    String result;
    if (task.isComplete) {
      if (task.isSuccessful) {
        result = 'Complete';
      } else if (task.isCanceled) {
        result = 'Canceled';
      } else {
        result = 'Failed ERROR: ${task.lastSnapshot.error}';
      }
    } else if (task.isInProgress) {
      result = 'Uploading';
    } else if (task.isPaused) {
      result = 'Paused';
    }
    return result;
  }

For determining progress, it uses:

  String _bytesTransferred(StorageTaskSnapshot snapshot) {
    return '${snapshot.bytesTransferred}/${snapshot.totalByteCount}';
  }

Which is then used in the build() method like this:

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<StorageTaskEvent>(
      stream: task.events,
      builder: (BuildContext context,
          AsyncSnapshot<StorageTaskEvent> asyncSnapshot) {
        Widget subtitle;
        if (asyncSnapshot.hasData) {
          final StorageTaskEvent event = asyncSnapshot.data;
          final StorageTaskSnapshot snapshot = event.snapshot;
          subtitle = Text('$status: ${_bytesTransferred(snapshot)} bytes sent');
        } else {
          subtitle = const Text('Starting...');
        }

So this takes the events stream of the task and gets the progress information from there.