简体   繁体   中英

Can't Link Storage Firebase images, to Cloud Firestore correctly

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;
      });
    }
  }

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM