简体   繁体   中英

How to download images from firebase storage to current user Cloud Firestore Flutter?

This is the code used to save a chosen image from image picker to firebase storage.

Future uploadPic(BuildContext context) async {
    String fileName = basename(_image.path);
    StorageReference firebaseStorageRef =
        FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    setState(() {
      print("Profile Picture uploaded");
      Scaffold.of(context)
          .showSnackBar(SnackBar(content: Text('Profile Picture Uploaded')));
    });
  }

Upon choosing an image as an authenticated user (I took care of authentication already) how can I convert the image as a URL for the current user's cloud firestore from which that image can appear in different areas of the app?

I save user information via the current user's uid as such for further context:

Future<void> userSetup(String displayName) async {
  int plastics = 0;
  final CollectionReference users =
      FirebaseFirestore.instance.collection('Users');
  FirebaseAuth auth = FirebaseAuth.instance;
  String uid = auth.currentUser.uid.toString();
  users.doc(uid).set({'displayName': displayName, 'uid': uid});
  users.doc(uid).update({'plastics': plastics});
  return;
}

Posting as Community Wiki, based in the comments.

You can use the below code - adapted for your needs, based in this answer here - to save an image into Firestore.

Future Build() async {
    String fileName = basename(_image.path);
    StorageReference reference = storage.ref().child('image');
    StorageUploadTask uploadTask = reference.putFile(fileName);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl1 = url;
    return url;
}

With the function written this way, you should be able to save the image from a specific path into your database. In addition to that, bear in mind that this code should be a starting point for you, as changes might be needed, considering variable names and locations.

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