flutter - 您如何调用一个未来,然后将该返回值传递给另一个未来以运行?
问题描述
我正在尝试用我的 Android 相机拍照,将该照片上传到 Google Firebase 存储,在存储上获取该图像的可下载 URL,并在 Firestore 上更新用户的照片供稿。如果我只调用 takeImage() 它会获取图像并成功上传到存储。如果我使用虚拟图像 url 调用 _uploadImage,它会正确更新提要。但是我无法将 takeImage 的结果作为参数传递给 _uploadImage()。
void takeAndSave() async {
url = await takeImage();
_uploadImage(url);
}
Future<String> takeImage() async {
// open camera
var image = await ImagePicker.pickImage(source: ImageSource.camera);
// save image to temp storage
final String fileName = "${Random().nextInt(10000)}.jpg";
Directory directory = await getApplicationDocumentsDirectory(); // AppData folder path
String appDocPath = directory.path;
// copy image to path
File savedImage = await image.copy('$appDocPath/' + fileName);
// upload file to Firebase Storage
final StorageReference ref = FirebaseStorage.instance.ref().child(fileName);
final StorageUploadTask task = ref.putFile(savedImage);
String downloadURL = await ref.getDownloadURL();
url = downloadURL;
// _image = image;
return downloadURL;
}
Future<void> _uploadImage(String url) async {
final FirebaseUser user = await widget.auth.currentUser();
String uid = user.uid;
print('uid = ' + uid);
print(url);
// upload URL to Firebase Firestore Cloud Storage
Firestore.instance.runTransaction((Transaction transaction) async {
DocumentReference _newPhoto = Firestore.instance.collection('users').document(user.uid);
await _newPhoto.collection('cards').add({"url" : url});
});
}
解决方案
根据您的代码,它应该可以正常工作,但是您的 takeImage() 方法可能会返回异常。尝试捕获该异常,看看它是否有帮助。
以下引用自https://www.dartlang.org/tutorials/language/futures#async-await
如果 Future-returning 函数以错误完成,您可能希望捕获该错误。异步函数可以使用 try-catch 处理错误:
Future<String> takeImage() async {
try {
// Your code
} catch (e) {
// Handle error...
}
}
推荐阅读
- javascript - Firestore 给出 ERROR FirebaseError: Missing or enough permissions。即使在规则操场上工作正常
- python - 用于 CLI 开发的 Python 框架
- java - Mockito:根据预期对象的集合模拟结果集
- ios - 查找 lat/lng 和半径 ios 的用户
- powershell - 如何在 powershell 中正确创建和修改元组哈希集?
- android - 为什么文本对齐在颤动中不起作用?
- flutter - 如何将flutter web连接到mysql
- sql - 如何在一张桌子内找到中转航班?
- python - 计算六边形中的三角形
- android - 从 Graphview 动态添加和删除数据