skip to Main Content

I need to get and save the document Id from a newly created document. How do I return this id from the Future or how do I add the docRef.id to the client provider?

  Future<void> saveNewClient(client) async {
    try {
      DocumentReference docRef = await _db.collection('client').add(client);
      client.updateClientId(docRef.id);  <<<< CLIENT PROVIDER
    } catch (e) {
      print(e);
    }
    return;
  }

This code does not throw an error but it never reaches the client.updateClientId(docRef.id) line. The save works so I should be able to get the docRef.id.

Why is this line being skipped?

2

Answers


  1. After creating a document, you can retrieve its document ID from the DocumentReference object returned by the add() method.

    Future<void> createDocument() async {
    
    FirebaseFirestore firestore = FirebaseFirestore.instance;
    
    DocumentReference docRef =
      await firestore.collection('YOUR_COLLECTION_NAME').add(YOUR_MAP).then(
    (docRef) {
      print('${docRef.id}');
    },
     );}
    
    Login or Signup to reply.
  2. There are a few ways to achieve this depending your preference or use case

     Future<String?> saveNewClient(client) async {
        FirebaseFirestore _db = FirebaseFirestore.instance;
        try {
    
          /// You can generate a document id before the create operate
          String id = _db.collection("client").doc().id;
    
          /// pass the generated id to the doc reference and set it
          /// .toMap() -> Assuming your client isn't of type map
          await _db.collection('client').doc(id).set(client.toMap());
          /// upon success return the id
          return id;
        } catch (e) {
          print(e);
          /// or return null if the operation failed
          return null;
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search