flutter - Dart 返回 Future.value 始终为 null
问题描述
我正在尝试从 Firebase 存储文件构建一个 URL,但Future<String>
我构建的似乎总是返回null
。这是Future
我打电话的:
Future<String> getUrlFromStorageRefFromDocumentRef(
DocumentReference docRef) async {
try {
docRef.get().then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
String filename = documentSnapshot.get('file');
firebase_storage.Reference ref = firebase_storage
.FirebaseStorage.instance
.ref()
.child('/flamelink/media/$filename');
if (ref == null) {
return Future.error("Storage Reference is null");
} else {
print(ref.fullPath);
return Future.value(
'https://storage.googleapis.com/xxxxxxxxx.appspot.com/${ref.fullPath}');
}
} else {
return Future.error('No Snapshot for DocumentReference ${docRef.id}');
}
});
} catch (e) {
print(e);
return Future.error('No DocumentReference for ID ${docRef.id}');
}
}
有问题的行是:
return Future.value(
'https://storage.googleapis.com/xxxxxxxxx.appspot.com/${ref.fullPath}');
值得注意的是,它String
是从Firebase Storage
路径生成的,在返回值之前,一切看起来都很完美。
它应该将String
值返回给我的调用代码,目前看起来像这样:
DocButtonCallback docCallback = () async {
bool isKidsDoc = item.screenId == StringsManager.instance.screenIdKids;
try {
// first we need to get the URL for the document ...
var url = await AssetManager.instance
.getUrlFromStorageRefFromDocumentRef(isKidsDoc
? feature.relatedDocumentKidsRef
: feature.relatedDocumentRef);
String urlString = url.toString();
canLaunch(urlString).then((value) {
launch(urlString);
}).catchError((error) {
// TODO: open alert to tell user
});
} catch (error) {
print(error);
}
};
我尝试了许多不同的方法来获得它,String
包括:
DocButtonCallback docCallback = () async {
bool isKidsDoc = item.screenId == StringsManager.instance.screenIdKids;
await AssetManager.instance
.getUrlFromStorageRefFromDocumentRef(isKidsDoc
? feature.relatedDocumentKidsRef
: feature.relatedDocumentRef)
.then((urlString) {
canLaunch(urlString).then((value) {
launch(urlString);
}).catchError((error) {
// TODO: open alert to tell user
});
}).catchError((error) {
// TODO: open alert to tell user
});
};
出于某种原因,Future
总是返回null
。我在这里做错了什么?
解决方案
您Future
在then()
回调中返回值,它本质上是从回调本身而不是从您的getUrlFromStorageRefFromDocumentRef()
函数返回这个值。在那里,您只需要在此之前添加一个 return 语句:
当前的:
docRef.get().then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
...
后:
/// Adding the return statement here to return the actual value
/// returned internally by the then callback
return docRef.get().then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
...
如果您将鼠标悬停在then()
回调上,您的 IDE 应显示此回调将返回Future<T>
(或任何通用类型占位符),也需要返回以使其可用
推荐阅读
- java - 将带偏移量的时间转换为 UTC 并返回 localdatetime
- azure-pipelines - 如何修复端点管理员意外失去权限的端点?
- c++ - 无法从基于 libstdc++ 策略的数据结构中删除
- angular - Angular 2 稍后将表单控件转换为表单组
- http - 如何实现 HTTP 中继/隧道来访问 Web 应用程序?
- forms - 仍然无法使用 Symfony 验证收集表单
- angular - 为什么设置 cookie 不能与来自外部 API 的角度和服务工作者一起使用
- python-3.x - 如何检查字符串是否仅包含字母或仅包含数字?
- api - 如何使用 __groovy 评估 java 函数并将其分配为 Http Request 的一部分
- jmeter - 在 JMeter 5.2 中使用 CEGID 应用程序记录