skip to Main Content

I am trying to get the document id of my collection "blogs" in firebase . I tried to access it using id method but it is showing an error Cannot read properties of undefined (reading 'id').How can I access the document id?

this is how I tried to print the document id print(docRef.id); but getting the error .What’s wrong with my code?

DocumentReference docRef =
                            await FirebaseFirestore.instance
                                .collection('blogs')
                                .add({
                                  'title': titleController.text,
                                  'body': myController.text,
                                  'author': name,
                                 
                                  'date': DateFormat('dd/MM/yyyy,hh:mm')
                                      .format(DateTime.now()),
                                })
                                .then((value) => successAlert(context))
                                .catchError((error) => errorAlert(context));

                       print(docRef.id);

                        titleController.clear();
                        myController.clear();
                      }

2

Answers


  1. well, while you’re using then, try this instead :

                                await FirebaseFirestore.instance
                                    .collection('blogs')
                                    .add({
                                      'title': titleController.text,
                                      'body': myController.text,
                                      'author': name,
                                     
                                      'date': DateFormat('dd/MM/yyyy,hh:mm')
                                          .format(DateTime.now()),
                                    })
                                 .then((value) {
                                 print(value.id); // do it here
                                 successAlert(context);
                                 })
                                    .catchError((error) => errorAlert(context));
    
    Login or Signup to reply.
  2. If you want to get the data after FirebaseFirestore method you need to use this approach instead of using then method:

    DocumentReference docRef = await FirebaseFirestore.instance .collection('blogs').add({
        'title': titleController.text,
        'body': myController.text,
        'author': name,
        'date': DateFormat('dd/MM/yyyy,hh:mm').format(DateTime.now()),})
       .catchError((error) => errorAlert(context));
    
    successAlert(context)
    print(docRef.id);
    titleController.clear();
    myController.clear();
    

    when you use then to get an async value you only get that result inside then and can’t access it after then.

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