[英]how do I create a progress bar in flutter firebase
我無法創建進度條來指示我將圖像上傳到 firebase 存儲的過程。
Future getImage(BuildContext context) async {
final picker = ImagePicker();
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
_image = File(pickedFile.path);
});
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child('profile/${Path.basename(_image.path)}}');
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
setState(() {
_imageURL = dowurl.toString();
});
print(_imageURL);
}
這是我為上傳圖像並獲取圖像 URL 而編寫的代碼。 希望有人能幫助我謝謝!
您可以在您的uploadTask
上收聽events
。
這里:
uploadTask.events.listen((event) {
setState(() {
_progress = event.snapshot.bytesTransferred.toDouble() /
event.snapshot.totalByteCount.toDouble();
});
}).onError((error) {
// do something to handle error
});
現在您可以像這樣顯示進度:
Text('Uploading ${(_progress * 100).toStringAsFixed(2)} %')
創建進度條:
LinearProgressIndicator(
value: _progress,
)
希望有幫助。
使用 Future Builder 並將這個 getImage 傳遞給 future builder Future Builder Example
或者您可以使用模態進度 HUD
Ayush Shekhar 的答案是正確的,但由於 firebase 插件的快速更新,某些部分已經過時。
在 state class 之上
double? _progress;
...在上傳方法中,您可以這樣設置。
uploadTask.snapshotEvents.listen((event) {
setState(() {
_progress =
event.bytesTransferred.toDouble() / event.totalBytes.toDouble();
print(_progress.toString());
});
if (event.state == TaskState.success) {
_progress = null;
Fluttertoast.showToast(msg: 'File added to the library');
}
}).onError((error) {
// do something to handle error
});
您可以像這樣獲取下載鏈接。
uploadTask.then((snap) async {
final downloadURL = await snap.ref.getDownloadURL();
print(downloadURL);
});
...
像這樣在 UI 中使用 _progress。
if (_progress != null)
LinearProgressIndicator(
value: _progress,
minHeight: 2.0,
color: Constants.primaryColor,
),
檢查這個,它適用於視頻和圖像:
final fil = await ImagePicker().pickVideo(source: ImageSource.gallery);
final file = File(fil!.path);
final metadata = SettableMetadata(contentType:"video/mp4");
final storageRef = FirebaseStorage.instance.ref();
final uploadTask = storageRef
.child("images/path/to/video")
.putFile(file, metadata);
// Listen for state changes, errors, and completion of the upload.
uploadTask.snapshotEvents.listen((TaskSnapshot taskSnapshot) {
switch (taskSnapshot.state) {
case TaskState.running:
final progress =
100.0 * (taskSnapshot.bytesTransferred / taskSnapshot.totalBytes);
print("Upload is $progress% complete.");
break;
case TaskState.paused:
print("Upload is paused.");
break;
case TaskState.canceled:
print("Upload was canceled");
break;
case TaskState.error:
// Handle unsuccessful uploads
break;
case TaskState.success:
print("Upload is completed");
// Handle successful uploads on complete
// ...
break;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.