我正在尝试在进度指示器中显示我上传到 firebase 存储的文件的进度,如何实现此目的。?
请注意,我是同时上传两个文件。
这是我的代码。
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());
}
}
首先采用变量
bool load
并在函数开始时进行初始化 load=false
make load=true
然后在函数结束时 load=false,所以在你的父小部件上 load==true?CircularProgressIndicator():Scaffold(),
所以你在这里发挥作用
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;
})
}
}
您只需使用以下代码即可跟踪上传进度:
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);
});
做这样的事情:
// 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();