如何在用户离线时尝试将数据添加/上传到 Firebase 时显示错误?
Posted
技术标签:
【中文标题】如何在用户离线时尝试将数据添加/上传到 Firebase 时显示错误?【英文标题】:how to show error when trying to add/upload data to firebase in flutter when user is offline? 【发布时间】:2020-11-10 02:19:57 【问题描述】:当用户尝试添加文档或将图像上传到 firestore 云/firebase 存储时,我基本上是在尝试显示警报对话框。我尝试使用 try 和 catch 块以及 .catchError() 进行尝试,但它不起作用,它基本上是在获得 Internet 连接后执行此操作。我想要做的是显示一个警报对话框并取消该过程,即使用户恢复连接(他必须再次重复上传过程)。这是我的代码示例:
这是用于挑选和上传图片:
Future _getImage(bool isCamera) async
var pickedImage;
try
if (isCamera)
pickedImage =
await picker.getImage(source: ImageSource.camera, imageQuality: 20);
else
pickedImage = await picker.getImage(
source: ImageSource.gallery, imageQuality: 20);
if (pickedImage != null)
_uploadAndSetUrl(File(pickedImage.path));
catch (e)
print('error here');
Future _uploadAndSetUrl(File image) async
try
_uploadingStatus(true);
StorageUploadTask uploadTask = _bookImageRef.putFile(image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
String downloadAddress = await _bookImageRef.getDownloadURL();
_uploadingStatus(false);
setState(()
_imageUrl = downloadAddress;
);
print(_imageUrl);
on PlatformException catch (e)
print('error: $e');
catch (e)
print('No image added');
还有另一种将文档添加到 Firestore 云的方法。有什么办法吗?
提前谢谢你!
【问题讨论】:
【参考方案1】:试试这个,
import 'dart:io';
Future _getImage(bool isCamera) async
var pickedImage;
try
if (isCamera)
pickedImage =
await picker.getImage(source: ImageSource.camera, imageQuality: 20);
else
pickedImage = await picker.getImage(
source: ImageSource.gallery, imageQuality: 20);
if (pickedImage != null)
try
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty)
_uploadAndSetUrl(File(pickedImage.path));
on SocketException catch (_)
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text("Connection Error !"),
content: Text("Please connect to the internet."),
)
);
catch (e)
print('error here');
【讨论】:
如果有帮助请告诉我以上是关于如何在用户离线时尝试将数据添加/上传到 Firebase 时显示错误?的主要内容,如果未能解决你的问题,请参考以下文章
Firebase 离线支持:在用户离线时上传帖子,当用户在 iOS Swift 应用程序中在线时同步