How to store image URL (from Firebase storage) to Firestore [Flutter]

977

Use this function to get download url of uploaded image. Then store them in a location in firestore. You can use same identifier in firestore with storage.

 Future <String> _uploadphotofile(mFileImage) async {
            final  Reference storageReference = FirebaseStorage.instance.ref().child("products");
            UploadTask uploadTask = storageReference.child("product_$productId.jpg").putFile(imgfile);
        
            String url = await (await uploadTask).ref.getDownloadURL();
            return url;
          }
Share:
977
MikiMeow_
Author by

MikiMeow_

new to flutter :)

Updated on December 31, 2022

Comments

  • MikiMeow_
    MikiMeow_ over 1 year

    I'm new to Flutter. I'm currently developing my flutter project. Basically, my project have a register page, login page, and profile page. User have to fill in some details, and choose a temporarily avatar (example: 1, 2, 3...) in register page. All details will save to Firestore once they click "Register" button. After user login, the chosen avatar will appear as user profile picture, and user can change it later.

    This is how my register page looks like. The avatar is in horizontal list view, with numbers. User can choose avatar and enter at TextFormField below. Avatar displaying here is asset image. Register Page

    I have uploaded those avatar to my Firebase Storage. Firebase Storage

    So the problem I'm facing now is, I don't know how to save the photo URL to Firestore. Instead of storing number and I assign URL by myself, I want the image Firebase Storage URL be stored in Firestore together with user details. So in future, user can change their profile picture after they login.

    Here is short code on register page (upload details to Firestore part):

      FirebaseAuth _auth = FirebaseAuth.instance;
      FirebaseFirestore _fires = FirebaseFirestore.instance;
      final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
      final idController = TextEditingController();
      final nameController = TextEditingController();
      final emailController = TextEditingController();
      final avatarController = TextEditingController();
    
      String _studentid, _name, _email, _password, _avatar;
    
      _register() async {                         // ---> (register button) onPressed: _register,
          if (_formKey.currentState.validate()) {
          _formKey.currentState.save();
    
          _auth.createUserWithEmailAndPassword(
              email: _email, password: _password).then((currentUser) =>
              _fires.collection("users").doc(_auth.currentUser.uid).set({
            "uid": _auth.currentUser.uid,
            "Name": "$_name",
            "Email": "$_email",
            "Avatar": "$_avatar"  //only store numbers now (avatar 1, 2, 3, ...)
            }).then((result) => {
            //a page that show registration success, then back to login page
              Navigator.pushReplacementNamed(context, "RegisterComplete"), 
                idController.clear(),
                nameController.clear(),
                emailController.clear(),
                avatarController.clear()
            }).catchError((e) => print(e)))
              .catchError((e) => showError(e.message));
        }
      }
    

    (textformfield for entering avatar number part):

    Container(
       child: TextFormField(
          validator: (input) {
             if (input.length != 1) return 'Please choose your avatar';
             return null;},
          keyboardType: TextInputType.number,
          inputFormatters: <TextInputFormatter>[
             FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),],
          controller: avatarController,
          decoration: InputDecoration(
             labelText: 'Avatar',
             labelStyle: TextStyle(
             fontSize: 18,
             color: Color(0xFF2C4D83),
          ),
          prefixIcon: Icon(Icons.face, color: Color(0xFF2C4D83),),
       ),
       onSaved: (String value) => _avatar = value),
     ),
    

    I think I have to create a condition, if the input _avatar = 1, then URL will be "gs://.../avatar1.jpg", and store into Firestore, but I have no idea how should I write it, and where should the code be placed.

    Really appreciate if anyone can help me or provide me some direction. Thanks.

  • MikiMeow_
    MikiMeow_ over 2 years
    Thanks, I get what you mean, but what if I have total 10 pictures, with conditions if the user enter "1" in textFormField, means user choose "avatar1.jpg", if user enter "2" means "avatar2.jpg", after user choose avatar only get the url and store in firestore?
  • Muhtar
    Muhtar over 2 years
    You can go with a collection lets say "avatarcollection". Store their url with its name. When a user types 1 you can call avatar1 element from avatarcollection and you can reach its url from field. Then store the url under user's properties in firestore.