Reputation: 87
I am trying to show the progress of the file I am uploading to firebase storage in a progress indicator how can I achieve this.?
Note that I am a uploading two files at the same time.
here is my code.
Future<String?> _uploadFileToStorage(BuildContext context,File file, path) async {
try {
var task = _firebaseStorage.ref().child(path);
var status = await task.putFile(file);
print(status.state);
return task.getDownloadURL();
} catch (err) {
print(err.toString());
}
}
Upvotes: 1
Views: 2460
Reputation: 1026
Do something like this:
// gets the upload task for the current image
UploadTask? task = await uploadFileToFirebase("images", File(image.path));
// updates the upload progress
task.snapshotEvents.listen((event) {
upload_progress = event.bytesTransferred.toDouble() / event.totalBytes.toDouble() * 100;
print("upload progress is $upload_progress");
notifyListeners();
}).onError((error) {
print("there was an error boss $error");
});
// uploads the file (image or video) to firebase
final snapshot = await task.whenComplete(() => {});
// gets the file's (image or video) url
String media_url = await snapshot.ref.getDownloadURL();
Upvotes: 0
Reputation: 329
You can track the uploading progress by simply using the following code:
status.snapshotEvents.listen((TaskSnapshot snapshot) {
print('Task state: ${snapshot.state}');
print('Progress: ${(snapshot.bytesTransferred / snapshot.totalBytes) * 100} %');
switch (snapshot.state) {
case TaskState.paused:
// TODO: Handle this case.
break;
case TaskState.running:
return CircularProgressIndicator(
value: (snapshot.bytesTransferred > 0 && snapshot.totalBytes > 0) ? snapshot.bytesTransferred / snapshot.totalBytes : null);
break;
case TaskState.success:
// TODO: Handle this case.
break;
case TaskState.canceled:
// TODO: Handle this case.
break;
case TaskState.error:
// TODO: Handle this case.
break;
}
}, onError: (e) {
// The final snapshot is also available on the status via `.snapshot`,
// this can include 2 additional states, `TaskState.error` & `TaskState.canceled`
print(status.snapshot);
});
Upvotes: 1
Reputation: 661
first take variable bool load
and make initialy load=false
when your function start make load=true
and at then end of your function load=false, so on your parent widget load==true?CircularProgressIndicator():Scaffold(),
so here you function
Future<String?> _uploadFileToStorage(BuildContext context,File file, path) async {
try {
setState({
load=true;
});
var task = _firebaseStorage.ref().child(path);
var status = await task.putFile(file);
print(status.state);
return task.getDownloadURL();
setState({
load=false;
})
} catch (err) {
print(err.toString());
setState({
load=false;
})
}
}
Upvotes: 2