我看到有很多关于如何使用flutter上传图像到firebase存储的例子,但没有关于实际下载/读取/显示已经上传的图像的内容.
在Android中,我只是用来Glide显示图像,我如何在Flutter中这样做?我是否使用NetworkImage该类,如果是,我如何首先获取存储在存储中的图像的URL?
Ale*_*hov 12
下面是一个有状态小部件的示例,它从 Firebase Storage 对象加载图像并构建一个 Image 对象:
class _MyHomePageState extends State<MyHomePage> {
final FirebaseStorage storage = FirebaseStorage(
app: Firestore.instance.app,
storageBucket: 'gs://my-project.appspot.com');
Uint8List imageBytes;
String errorMsg;
_MyHomePageState() {
storage.ref().child('selfies/me2.jpg').getData(10000000).then((data) =>
setState(() {
imageBytes = data;
})
).catchError((e) =>
setState(() {
errorMsg = e.error;
})
);
}
@override
Widget build(BuildContext context) {
var img = imageBytes != null ? Image.memory(
imageBytes,
fit: BoxFit.cover,
) : Text(errorMsg != null ? errorMsg : "Loading...");
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new ListView(
children: <Widget>[
img,
],
));
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,FirebaseApp初始化由Firestore类处理,因此不需要进一步的初始化代码。
要查看存储中的图像,您需要的是存储中文件的名称。获得所需特定图像的文件名后。就我而言,如果我想加载testimage,
final ref = FirebaseStorage.instance.ref().child('testimage');
// no need of the file extension, the name will do fine.
var url = await ref.getDownloadURL();
print(url);
Run Code Online (Sandbox Code Playgroud)
输入网址后,
Image.network(url);
Run Code Online (Sandbox Code Playgroud)
就这样 :)
更新
在较新的版本中使用
await ref.getDownloadURL();
Run Code Online (Sandbox Code Playgroud)
请参阅如何从Flutter中的UploadTaskSnapshot获取完整的downloadUrl?
原版的
someMethod() async {
var data = await FirebaseStorage.instance.ref().child("foo$rand.txt").getData();
var text = new String.fromCharCodes(data);
print(data);
}
Run Code Online (Sandbox Code Playgroud)
要么
final uploadTask = imageStore.putFile(imageFile);
final url = (await uploadTask.future).downloadUrl;
Run Code Online (Sandbox Code Playgroud)
在后一种情况下,您需要存储downloadUrl某处,然后使用NetworkImage或类似地将其渲染.
| 归档时间: |
|
| 查看次数: |
9792 次 |
| 最近记录: |