elios_cama
elios_cama

Reputation: 217

How to store doc id when creating it using flutter and firestore

I'm creating a Todo App and I need to access the ids of my documents stored in firestore in order to delete them. But I can't figure out how to save it when I'm creating it. Here's the part in my Add screen where I create a new document.

 _firestore.collection('todos').add({
                    'title' : title,
                    'type' : type,
                    'date' : dayDate,
                    'time' : _dayTime,
                    'category' : category,
                    'author' : loggedInUser.uid,
                    //'id' : doc.id
                  
                  });

I don't know how to acess it. And also I display my tasks into cards and when i long press them I want them to delete from firestore but I can't bc I don't have their idea. Here's my empty function:

void deleteTask(){
_firestore.collection("todos").doc().delete();
}

If you have any ideas please tell me. Thanks guys!

Upvotes: 4

Views: 2984

Answers (4)

Luis Vargas
Luis Vargas

Reputation: 1

first I update the document, that is, I save the collection, second it is updated, here is the example, I hope it helps you: Although there are two queries, I think it saves us from not using more in the future:

DocumentReference<Map<String, dynamic>> newOrderRefA =
                      await FirebaseFirestore.instance
                          .collection('ordenes')
                          .add({
                    'fecha': DateTime.now(),
                    'sectorEntrega': sectorIngresado,
                    'nombreLocal': nombreLocal,
                    'uidCuestomer': user.uid,
                    'phoneLocal': numeroLocal,
                    'tokenNotificacion': userToken,
                    'stateOrder': 'open',
                    'metodoPagoEfectivoRealizada': metodoPagoSeleccionado,
                    'esNoViableEntrega': false,
                    'province': provinceLocal,
                    'sectorWork': sectorWork,
                  });
                  print(newOrderRefA.id);
                  String uidOrden = newOrderRefA.id;

                  await FirebaseFirestore.instance
                      .collection('ordenes')
                      .doc(newOrderRefA.id)
                      .update({'uidOrden': uidOrden});

Good Luck

Upvotes: 0

Ahmed Raafat
Ahmed Raafat

Reputation: 197

CollectionReference ref =
    await FirebaseFirestore.instance.collection('todos');

String docId=ref.doc().id;

await ref.doc(docId).set({
  'title' : title,
  'type' : type,
  'date' : dayDate,
  'time' : _dayTime,
  'category' : category,
  'author' : loggedInUser.uid,
  'id' : docId
});

Upvotes: 6

Zeeshan Ahmad
Zeeshan Ahmad

Reputation: 676

Sorry, I'm a bit late but If anyone else is stuck here is how you can store doc id when creating it

CollectionReference ref =
        FirebaseFirestore.instance.collection('todos');

    await ref.doc(ref.doc().id).set({
                    'title' : title,
                    'type' : type,
                    'date' : dayDate,
                    'time' : _dayTime,
                    'category' : category,
                    'author' : loggedInUser.uid,
                    'id' : ref.doc().id
                  
                  }).then((value) {
            // Do something
    }).onError((error, stackTrace) {
      print(stackTrace);
    });

To delete the specific collection

void deleteTask(){
  FirebaseFirestore.instance.collection('todos').doc(docId).delete();
}

Upvotes: 1

M.M.Hasibuzzaman
M.M.Hasibuzzaman

Reputation: 1151

You can get the doc id before like so CollectionRef.pots.doc().id you can then add it. This way you will have the docId also inside the doc which you can access when you have the doc data..

 static createPot(String name, String password) async{
    try{
      PotModel newPot = PotModel(
        name: name,
        potId: FirebaseFirestore.instance.collection('pots').doc().id, // will generate a random doc id, which will be used to create the next document
        password: password,
        ownerId: ViewModelUser.user.value.mobile,
        createdAt: Timestamp.now(),
        isActive: true,
        potActions: [],
        users: [ViewModelUser.user.value.mobile]
      );
      /// creating a new pot
      DocumentReference documentReference = await FirebaseFirestore.instance.collection('pots').add(newPot.toJson());

      return newPot;
    }catch(e){
      print(e.toString());
      return null;
    }
  }

Upvotes: 5

Related Questions