Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the document id after adding document in Cloud Firestore in Dart

Im using the following code to update a Cloud Firestore collection using Dart/Flutter.

  final docRef = Firestore.instance.collection('gameLevels');
  docRef.document().setData(map).then((doc) {
    print('hop');
  }).catchError((error) {
    print(error);
  });

I'm trying to get the documentID created when I add the document to the collection but the (doc) parameter comes back as null. I thought it was supposed to be a documentReference?

Since it's null, I obviously can't use doc.documentID.

What am I doing wrong?

like image 788
JustLearningAgain Avatar asked Jun 27 '18 04:06

JustLearningAgain


1 Answers

@Doug Stevenson was right and calling doc() method will return you document ID. (I am using cloud_firestore 1.0.3)

To create document you just simply call doc(). For example I want to get message ID before sending it to the firestore.

  final document = FirebaseFirestore.instance
      .collection('rooms')
      .doc(roomId)
      .collection('messages')
      .doc();

I can print and see document's id.

print(document.id)

To save it instead of calling add() method, we have to use set().

  await document.set({
    'id': document.id,
    'user': 'test user',
    'text': "test message",
    'timestamp': FieldValue.serverTimestamp(),
  });
like image 110
ShadeToD Avatar answered Oct 19 '22 01:10

ShadeToD