2
votes

I dont understand why I am not able to link and send the URL to the cloud firestore collection document the image is picked up correctly in Storage but cant get URL in cloud firestore db here is my code:


  bool isLoading = false;
  var firebaseUser =  FirebaseAuth.instance.currentUser;


  Future uploadImage(BuildContext context) async {
    String fileName = basename(_imageFile.path);
    Reference firebaseStorageRef =
    FirebaseStorage.instance.ref().child('uploads/$fileName');
    UploadTask uploadTask = firebaseStorageRef.putFile(_imageFile);
    TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() => null);
    if (taskSnapshot == null) {
      final String downloadUrl =
      await taskSnapshot.ref.getDownloadURL();
      await FirebaseFirestore.instance.doc(firebaseUser.uid)
          .collection("influncerUser")
          .add({"imageUrl": downloadUrl,});
      setState(() {
        isLoading = true;
      });
    }
  }

1

1 Answers

2
votes

First, why to use if (taskSnapshot == null) ? If the taskSnapshot is null you can't fetch the download url, so delete it.

Second, prefer use onComplete instead of .whenComplete(() => null)

Future uploadImage(BuildContext context) async {
String fileName = basename(_imageFile.path);
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('uploads/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(_imageFile);

// use onComplete to await when the doc has been pushed.
TaskSnapshot taskSnapshot = await uploadTask.onComplete;

final String downloadUrl = await taskSnapshot.ref.getDownloadURL();
await FirebaseFirestore.instance.doc(firebaseUser.uid)
    .collection("influncerUser")
    .add({"imageUrl": downloadUrl,});
setState(() => isLoading = true);

}