0
votes

I want to get the image-url and safe it in the cloud Firestore from Firebase in a String. Iam able to upload the image to the FirebaseStorage but I can´t safe the Image-url as a string to upload it than to my cloud Firestore.

Can someone help me with that problem?

<!-- language: lang-dart -->

//upload and get image
File imageFile;
  String imageURL;

  Future getImage (bool isCamera) async {
    File image;
    if(isCamera) {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    }else{
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    }
    setState(() {
      imageFile = image;
    });
  }

  Future uploadImage(BuildContext context) async {
    String fileName = basename(imageFile.path);
    StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = firebaseStorageRef.putFile(imageFile);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    setState(() {
      imageURL = await taskSnapshot.ref.getDownloadURL();
    });
  }

//upload to realtime Database
RaisedButton(
                  color: Theme.of(context).primaryColor,
                  textColor: Colors.white,
                  child: Text(isEditNote? "Update" : "Save"),
                  onPressed: () async{
                    if(_key.currentState.validate() && imageFile != null){
                      try {
                        if(isEditNote){
                          uploadImage(context);
                          Book book = Book(
                            image: imageURL,
                          );
                          FirestoreService().updateBook(book);
                          Navigator.pop(context);
                        }else {
                          uploadImage(context);
                          Book book = Book(
                            image: imageURL,
                          );
                          await FirestoreService().addBook(book);
                          Navigator.pop(context);}
                      }catch(e){
                        print(e);
                      }
                    }else{

                    }
                  },
1

1 Answers

1
votes

to get the imageUrl you can set it to

imageUrl = await taskSnapshot.ref.getDownloadURL() ;

as defined

getDownloadURL() → Future Asynchronously retrieves a long lived download URL with a revokable token. This can be used to share the file with others, but can be revoked by a developer in the Firebase Console if desired.

in the official documentation:

https://pub.dev/documentation/firebase_storage/latest/firebase_storage/StorageReference-class.html