'How to get the created file to be saved with a name that matches the user's email stored in Firebase Storage in flutter?

I want to save an image inside a folder with a name that matches with the users email when signing up.

The flow of the file in Firebase Storage is like this

usersProfilePic -> [email protected](users email) -> image_picker.jpg(the pic)

This is my code

uploadImage() async {
    //upload the image to storage
    var imageFile = FirebaseStorage.instance
        .ref()
        .child("usersProfilePic")
        .child("the email of the user")
        .child(basename(_image!.path));
    UploadTask task = imageFile.putFile(_image!);
    TaskSnapshot snapshot = await task;
    //for download
    url = await snapshot.ref.getDownloadURL();
    print(url);
  }

  //add user to firebase
  addUserToFirebase() async {
    await FirebaseAuth.instance
        .createUserWithEmailAndPassword(email: email, password: password)
        .then((value) {
      print(value.user!.uid);
      ScaffoldMessenger.of(this.context).showSnackBar(
        const SnackBar(
          backgroundColor: kSoftLimeGreen,
          content: Text(
            "Registered Successfully. Please Login..",
            style: TextStyle(fontSize: 20.0),
          ),
        ),
      );
      Navigator.pushReplacement(
        this.context,
        MaterialPageRoute(
          builder: (context) => const LoginPage(),
        ),
      );
    });
    await FirebaseFirestore.instance.collection('user').doc().set({
      'name': name,
      'phoneNumber': phoneNumber,
      'email': email,
      'password': password,
      'confirmPassword': confirmPassword,
      'imageProfileUrl': url,
    });
  }

All of the code is working as intended, I only need on how to save the image inside a folder with the users email as the name of the folder.

If you have any solution, please share with me. Thank you



Solution 1:[1]

Something like this should work:

if (FirebaseAuth.instance.currentUser != null) {
  var email = FirebaseAuth.instance.currentUser.email
  var imageFile = FirebaseStorage.instance
      .ref()
      .child("usersProfilePic")
      .child(email)
      .child(basename(_image!.path));
  ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1