parth shukla
parth shukla

Reputation: 117

How to upload image on cloud firestore linked to an entry?

I am trying to upload image on cloud firestore. But there is a error I am not able to catch.

I am using the code under uploadFile from here

 Future<void> getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      widget._image = image;
      print("added image");
    });
   uploadImage();
  }

  Future uploadImage() async {
    String fileName = DateTime.now().millisecondsSinceEpoch.toString();
    StorageReference reference = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = reference.putFile(widget._image);
    StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
    storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl) {
      widget.photourl = downloadUrl;
    }, onError: (err) {
      print('Error');
    });
  }

'added image' prints on the terminal, so there isn't a problem in that it seems.

photourl is null, but it should contain the url. enter image description here

Thank you.

Upvotes: 0

Views: 67

Answers (2)

parth shukla
parth shukla

Reputation: 117

It seems the problem was because of state of widget. This solved it

Future uploadImage() async {
    String fileName = DateTime.now().millisecondsSinceEpoch.toString();
    StorageReference reference = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = reference.putFile(widget._image);
    StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
    storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl) {

      setState(() {
        widget.photourl = downloadUrl;
      });

    }, onError: (err) {
      print('Error');
    });
  }

Upvotes: 0

Rudresh Narwal
Rudresh Narwal

Reputation: 3120

In the above code, you are just getting an image URL from Firebase storage. You need to update the photoURL in Firestore also.

Future<void> updateOneField = database
   .collection('entries')
   .document('D3idV9o7uWT4pWvby643')
   .updateData(
      {
      "photourl": downloadUrl
      });

Upvotes: 1

Related Questions