英文:
How to determine if there was no internet access while uploading media to Firebase storage
问题
我有以下代码
FirebaseStorage.instance.ref('fo').putData(data).then((value){
/// 完成
}).catchError((error){
/// 错误
});
现在如果没有网络,我想在我的UI状态中进行一些更改。经过多次测试,似乎FirebaseStorage
从不返回与互联网问题相关的错误。
英文:
i have the folliwng code
FirebaseStorage.instance.ref('fo').putData(data).then((value){
/// done
}).catchError((error){
/// error
});
now i want change some in my UI state if there was no Internet , after many tests it seems FirebaseStorage
never return errors related internet issues
答案1
得分: 1
通常,Firebase SDK 仅会抛出这些错误 处理错误消息
如果您想处理与连接问题相关的错误,您可以使用 connectivity 包,如下所示:
class _YourUploadScreenState extends State<YourUploadScreen> {
final FirebaseStorage _storage = FirebaseStorage.instance;
final Connectivity _connectivity = Connectivity();
void uploadData() async {
var connectivityResult = await _connectivity.checkConnectivity();
if (connectivityResult == ConnectivityResult.none) {
// 处理无网络连接的情况
// 相应地更新您的 UI 状态
return;
}
_storage.ref('fo').putData(data).then((value) {
/// 完成
}).catchError((error) {
/// 错误
});
}
}
但是,如果在上传对象时互联网连接中断,那么您必须处理此类情况:处理上传任务的进度和错误
更新:
您还可以使用 监视上传进度 错误与连接错误有关的 `TaskState.error`,文档中提到:
> 当上传失败时会发出此事件。这可能是由于网络超时、授权失败或您取消任务而发生。
我已测试了上述方法,在上传过程中断开互联网连接,我会收到此错误消息。
Cloud Storage 的 Firebase SDK 会在连接丢失和重新连接的情况下自动重试文件上传,上传不会在连接丢失时立即失败。
英文:
Usually the Firebase SDK only throw these errors Handle Error Messages
If you want to handle errors with connectivity issues you can use connectivity package as follows :
class _YourUploadScreenState extends State<YourUploadScreen> {
final FirebaseStorage _storage = FirebaseStorage.instance;
final Connectivity _connectivity = Connectivity();
void uploadData() async {
var connectivityResult = await _connectivity.checkConnectivity();
if (connectivityResult == ConnectivityResult.none) {
// Handle no internet connectivity here
// Update your UI state accordingly
return;
}
_storage.ref('fo').putData(data).then((value) {
/// done
}).catchError((error) {
/// error
});
}
}
But if internet connection drops when you are uploading an object then you have to handle such scenarios: Handle progress and errors with uploadTask
Update :
You can also use Monitor Upload Progress error regarding connectivity errors `TaskState.error` in which docs says :
> Emitted when the upload has failed. This can happen due to network timeouts, authorization failures, or if you cancel the task.
I have tested above method with disconnecting the internet while upload process and I get this error.
The Firebase SDK for Cloud Storage will automatically retry file uploads and resume in the case that the connection is lost and regained. The upload will not just immediately fail when the connection is lost.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论