我正在使用 Flutter 和 Firebase。我已成功使用如下方案将用户个人资料照片上传到 Firebase 存储:
用户/用户id.png
到目前为止,每当我需要显示用户个人资料图片时,我都必须先将其下载到本地;就像
final String fileName = uid + ".png";
Directory appDocDir = await getTemporaryDirectory();
String appDocPath = appDocDir.path;
final File file = File('$appDocPath/$fileName');
// clears the file
file.writeAsStringSync("");
final StorageReference ref = FirebaseStorage.instance.ref().child('users/' + fileName);
final StorageFileDownloadTask downloadTask = ref.writeToFile(file);
final int byteNumber = (await downloadTask.future).totalByteCount;
print("byteNumber : ${byteNumber}");
} catch(e) {
return null;
}
但是,我想知道是否可以跳过该步骤并仅使用 NetworkImage() 函数,例如:
final StorageReference ref = FirebaseStorage.instance.ref().child('users/' + user.uid + ".png");
String downloadURL = await ref.getDownloadURL();
downloadURL = Uri.decodeFull(downloadURL.toString());
print("FB Storage URL: $downloadURL");
return new NetworkImage(downloadURL);
它不起作用并抛出异常。
我正在尝试做什么;这可能吗?
最佳答案
您想要显示的图像的数据始终必须读入您想要显示它的应用程序中。但您不一定需要像现在一样自行处理下载。
Firebase 存储中的任何文件都有一个所谓的下载 URL。任何拥有此 URL 的人都可以读取该文件,而无需使用 Firebase 存储 SDK。这几乎就是互联网上大多数图像的样子,因此有很多库可以处理此类图像 URL。
例如,Flutter cookbook has a section on displaying images from the internet ,这表明 Image
小部件可以显示来自 URL 的图像,如下所示:
Image.network(
'https://raw.githubusercontent.com/flutter/website/master/_includes/code/layout/lakes/images/lake.jpg',
)
如果使用来自 Github 的图像,您还可以使用来自 Firebase Storage 的下载网址。
大多数应用程序在上传文件时都会将文件的下载 URL 存储在数据库中。如果您没有下载 URL,只有路径,则可以通过以下方式获取下载 URL:
final StorageReference ref = FirebaseStorage.instance.ref().child('users/' + fileName);
final Uri downloadUrl = await ref.getDownloadUrl();
我不是 Flutter 专家,因此该代码片段中可能存在一些问题。
关于firebase - 我必须从 Firebase 下载图像才能显示吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51552784/