Thoxh
Thoxh

Reputation: 149

Get DocumentID after adding data to Firestore - Flutter, Firebase

Hello I've following problem with my flutter project: I want to save several data in my Firebase Firestore. As you see in the code the both strings are saved in the database, when I click a button. My question is, how can I get the DocumentID of the saved values? I already found some answer at stack overflow but in my opinion Firebase is pretty complicated so I wanna ask with my code too.

class _HomeStatefulState extends State<HomeStateful> {
  final firestoreInstance = FirebaseFirestore.instance;
  CollectionReference users = FirebaseFirestore.instance.collection('users');

  Future<void> addUser() {
    return users.add({
      'firstname': firstnameController.text, 
      'name': nameController.text, 
    })
        .then((value) => print("User Added"))
        .catchError((error) => print("Failed to add user: $error"));

  }

Upvotes: 0

Views: 529

Answers (1)

Ros&#225;rio P. Fernandes
Ros&#225;rio P. Fernandes

Reputation: 11326

The value returned by the add() Future is actually a DocumentReference. So you can use it to get its id:

  Future<void> addUser() {
    return users.add({
      'firstname': firstnameController.text, 
      'name': nameController.text, 
    })
        .then((value) => print("User Added, id = " + value.id))
        .catchError((error) => print("Failed to add user: $error"));

  }

Upvotes: 4

Related Questions