Bisclavret
Bisclavret

Reputation: 1351

Flutter display firebase storage image from path

I have been reading some questions around this and I can't find anything really that is relevant to what I am trying to do, and what I am trying to do is very simple.

I have the path of an image file from Firebase Storage, say:

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

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

So the image file path will be something like:

b8sJ7cEHCFdjh46wZNp5xThbvVzz2/profile/image_picker209656937087714.jpg

I just want to display this image. That's all. How can I convert knowing the exact path to this file into an object of type Image?

Upvotes: 1

Views: 3048

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80952

You need to save the image first to Firebase Storage using putFile():

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

Then you get the url of the image in Firebase Storage and save it to Firestore, for example:

  final String downloadUrl =
      await snapshot.ref.getDownloadURL();
  await Firestore.instance
      .collection("images")
      .add({"url": downloadUrl, "name": imageName});

Then to display the image you can do the following:

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() will retrieve the data inside the collection, then Image.network will take the url of the image and display the image in the application.

Upvotes: 3

Related Questions