I am adding a new client document to my Cloud Firestore DB. After I add the document I need to get the new document id so I can use it to link that client to a new transaction.
The way I have been trying to do this is to get the documentId right after it is created.
Here is how I am doing this right now.
This is where I create the client document:
Future<String?> clientId =
firestoreService.saveNewClient(toMap(newClient));
The function above calls this function below. I get a Future back but I don't see any documentId in the Future when I look at in the debugger.
Future<String?> saveNewClient(client) async {
// Get the document ID of the new document so it can be
// added to the new transaction document.
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;
}
}
As far as I can tell the above function works correctly in that there are no error thrown but I don't see any value for the documented. The document get created in Firebase.
This is what I see in the debugger:
After I get the documentId back, I want to save the documentId into the clientNotifierProvider. So, right after I execute the "save" from the first code snippet above I want to execute this code:
ref.read(clientNotifierProvider.notifier).updateClientId(clientId as String);
How do I get the documentId so I can insert it into the clientNotifierProvider? Thanks
Instead of
Future<String?> clientId= firestoreService.saveNewClient(toMap(newClient);
Await the future use this to get the unboxed future:
String? clientId = await
firestoreService.saveNewClient(toMap(newClient));
Then update the provider:
if(clients != null){
ref.read(clientNotifierProvider.notifier).updateClientId(clientId);
}