Eind997
Eind997

Reputation: 467

How can I get the ID number of a document added to Firestore?

I'm trying to add a document to Firestore using Flutter/Dart and then add the ID number that Firestore gives it to a list. I've seen online that an old way would be use codeRef.documentID but this doesn't seem to work and the rest of the code in the places I find this seems to be using deprecated syntax. I was thinking of creating the document name myself which would give the ID number I need but this would not protect against clashes. Is there a way I should be doing this?

final codeRef = await FirebaseFirestore.instance.collection('codes').doc().set({
      'name': _codeName,
});

Upvotes: 0

Views: 52

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317302

set() returns a Future<void>, so it makes sense that codeRef.documentID wouldn't work. void doesn't have any properties.

You will want to get the ID from the DocumentReference returned by doc() before you write the document.

DocumentReference ref = FirebaseFirestore.instance.collection('codes').doc();
String id = ref.id;
ref.set(...);

Upvotes: 1

Merym
Merym

Reputation: 881

var _result = await FirebaseFirestore.instance.collection('codes').add({
  'name': _codeName});

String id = _result.id

Upvotes: 0

Related Questions