'How to save the document id in document field while creating it in Flutter Firebase

I am trying to save the document id in the a new field but if i use

'postId': _firebase.collection('Posts').doc().id,

this will generate a new id

any suggestions

 try {
                    _firebase.collection('Posts').add({
                      'content': _postContent.toString(),
                      'poster': logedInUser.uid,
                      'sentOn': FieldValue.serverTimestamp(),
                      'numOfComments': numberOfComments,
                      'votesNumber': numberOfVotes,
                      'duration': _defaultPostTime,
                      'phoneNumber': logedInUser.phoneNumber,
                      'postId': _firebase.collection('Posts').doc().id,
                    });
}

enter image description here



Solution 1:[1]

      String id = _firebase.collection('Posts').doc().id;
       try {
                    _firebase.collection('Posts').doc(id).set({ 
                      'content': _postContent.toString(),
                      'poster': logedInUser.uid,
                      'sentOn': FieldValue.serverTimestamp(),
                      'numOfComments': numberOfComments,
                      'votesNumber': numberOfVotes,
                      'duration': _defaultPostTime,
                      'phoneNumber': logedInUser.phoneNumber,
                      'postId': id,
                    });
       }

Solution 2:[2]

@MotasemX You can try this method also generate a unique id first using date and time or any other approach . then put unique id as doc id as well as your postId

String id = DateTime.now().microsecondsSinceEpoch.toString();
try {
                    _firebase.collection('Posts').doc(id).set({ 
                      'content': _postContent.toString(),
                      'poster': logedInUser.uid,
                      'sentOn': FieldValue.serverTimestamp(),
                      'numOfComments': numberOfComments,
                      'votesNumber': numberOfVotes,
                      'duration': _defaultPostTime,
                      'phoneNumber': logedInUser.phoneNumber,
                      'postId': id,
                    });
       }

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 Subair K
Solution 2 Ilyas Arafath