简体   繁体   中英

Firebase Storage URL is FutureString

in my flutter app, the user picture is loaded by Cached Network image command, which gets its url by stream builder from firestore.

I am trying to add the functionality to the user of changing his pic by pressing on the pic as following:

  1. Selecting his pic with image picker.
  2. upload it to firebase storage.
  3. updating firestore usercollection document with new image url.

I created the below code. The problem is getDownloadURL() is not returning actual string, but "Instance of 'Future'".

so the new link stored in firestore is not correct to be used by Cached Network Image.

how can I get the actual URl String?

My Future Function Code:

Future ChangeProfilePic() async {
  String newimageurl = "";
  FirebaseStorage storage = FirebaseStorage.instance;
  Reference ref =
      storage.ref().child("ProfileImages/$globaluserid".toString());
  CollectionReference userscollectionref =
      FirebaseFirestore.instance.collection('UsersCollection');
  final ImagePicker _picker = ImagePicker();
  final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
  File imagefile = File(image!.path);
  UploadTask uploadTask = ref.putFile(imagefile);
  uploadTask.whenComplete(() {
    newimageurl = ref.getDownloadURL().toString();
    print("Image Uploaded");
    userscollectionref
        .doc(globaluserid)
        .update({'User_image_link': newimageurl});
    print("Link is Updated");
  }).catchError((onError) {
    print("Error");
    print(onError);
  });
}

Like many calls in your code `` is an asynchronous call, whose result won't be available immediately, so it returns a Future that will at some point contain the value. You can use await to wait for such a Future to complete and get its value, similar to what you already do in await _picker.pickImage .

await ref.getDownloadURL().toString();

Another change to consider is that putFile returns a Task , but that is actually also a Future , which means that you can await that too.

Combining these two fact, you can simplify your code to:

final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
File imagefile = File(image!.path);
await ref.putFile(imagefile);
newimageurl = (await ref.getDownloadURL()).toString();
print("Image Uploaded");
userscollectionref
    .doc(globaluserid)
    .update({'User_image_link': newimageurl});
print("Link is Updated");

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