skip to Main Content

I am created a basic app for adding post where i need to store post id

I dont want to generate any id my own way, to know if there is a another way

here is my coding for adding post

IconButton(onPressed: () async {
                    await FirebaseFirestore.instance.collection("posts").doc().set(
                        {
                          'message':txtpost.text,
                          'postby':FirebaseAuth.instance.currentUser!.email,
                          'posttime':Timestamp.now(),
                          'likes':[],
                          'postid':?????// here how to get current document id
                        });
                    print('Post Added Successfully...');
                    txtpost.clear();

                  }, icon: Icon(Icons.send))

2

Answers


  1. You could use the ID that is automatically generated when calling the function doc when no path is provided.

    Therefore you could first get the reference of the doc and then store the post.

    Here is how the code could look like:

        IconButton(
                onPressed: () async {
                  final docRef =
                      FirebaseFirestore.instance.collection('posts').doc();
                  final docId = docRef.id;
                  docRef.set(
                    {
                      'message': txtpost.text,
                      'postby': FirebaseAuth.instance.currentUser!.email,
                      'posttime': Timestamp.now(),
                      'likes': [],
                      'postid': docId
                    },
                  );
                  print('Post Added Successfully...');
                  txtpost.clear();
                },
                icon: Icon(Icons.send),
              ),
    
    Login or Signup to reply.
  2. The code below should do it:

    IconButton(
            onPressed: () async {
              final documentRef = FirebaseFirestore.instance.collection('posts').doc();
              final documentId = documentRef.id;
                  await documentRef.set(
                      {
                        'message':txtpost.text,
                        'postby':FirebaseAuth.instance.currentUser!.email,
                        'posttime':Timestamp.now(),
                        'likes':[],
                        'postid': documentId
                      });
                  print('Post Added Successfully...');
                  txtpost.clear();
            },
            icon: Icon(Icons.send),
          ),
    

    Every document reference comes with an id. You can get this id and set it as the post id.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search