firebase - Flutter从路径显示Firebase存储镜像

标签 firebase flutter dart google-cloud-firestore firebase-storage

我一直在阅读有关此问题的一些问题,但找不到与我想做的事情真正相关的任何事情,而我想做的事情很简单。

我有Firebase Storage中图像文件的路径,例如:

SharedPreferences prefs = await SharedPreferences.getInstance();
String fileName = prefs.getString('currentProfileImage');

StorageReference storageReference = FirebaseStorage.instance
  .ref()
  .child(widget.currentUserUID.toString() + '/profile/' + fileName);

因此,图像文件路径将类似于:
b8sJ7cEHCFdjh46wZNp5xThbvVzz2/profile/image_picker209656937087714.jpg

我只想显示此图像。就这样。如何将知道此文件的确切路径转换为Image类型的对象?

最佳答案

您需要先使用putFile()将镜像保存到Firebase Storage中:

StorageTaskSnapshot snapshot = await storage
   .ref()
   .child(widget.currentUserUID.toString() + '/profile/' + fileName)
   .putFile(file)
   .onComplete;

然后,在Firebase Storage中获取图像的url并将其保存到Firestore,例如:
  final String downloadUrl =
      await snapshot.ref.getDownloadURL();
  await Firestore.instance
      .collection("images")
      .add({"url": downloadUrl, "name": imageName});

然后,要显示图像,您可以执行以下操作:
body: Container(
  padding: EdgeInsets.all(10.0),
  child: FutureBuilder(
    future: getImages(),
    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (snapshot.connectionState == ConnectionState.done) {
        return ListView.builder(
            shrinkWrap: true,
            itemCount: snapshot.data.documents.length,
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                contentPadding: EdgeInsets.all(8.0),
                title:
                    Text(snapshot.data.documents[index].data["name"]),
                leading: Image.network(
                    snapshot.data.documents[index].data["url"],
                    fit: BoxFit.fill),
              );
            });
      } else if (snapshot.connectionState == ConnectionState.none) {
        return Text("No data");
      }
      return CircularProgressIndicator();
    },
  ),
),

/// code here

  Future<QuerySnapshot> getImages() {
    return fb.collection("images").getDocuments();
  }
getImages()将检索集合中的数据,然后Image.network将获取图像的url并在应用程序中显示该图像。

关于firebase - Flutter从路径显示Firebase存储镜像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62231143/

相关文章:

javascript - 在 Firebase 的函数中获取访问 firestore 数据

sqlite - Flutter - 在哪里放置自己的 SQLite .db 文件?

visual-studio-code - 我在构建 flutter 项目时如何将 dart 和 flutter 设置为默认值

sql - 从数据库中获取数据并填充分区列表

javascript - ffmpeg 错误 : Can't make thumbnail from video in javascript

javascript - 你能写一个只被 GoogleBot 触发的 Firebase 函数吗?

android-activity - 当点击 Firebase 通知时显示特定的 Activity

dart - Flutter 更改文本框下划线颜色

dart - 聚合物表达式通过名称访问属性

android - Flutter 是否有上下文操作栏,用于从 ListView 中选择多个项目