Dart return Future.value is always null



我正试图从Firebase Storage文件构建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。我在这里做错了什么?

您在then()回调中返回Future值,它本质上是从回调本身而不是从getUrlFromStorageRefFromDocumentRef()函数返回该值。在此之前,您只需要添加一个返回语句:

当前:

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>(或任何通用类型的占位符(,这些占位符也需要返回才能使其可用

最新更新