Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get, set, update and delete data from the cloud firestore in Flutter?

I tried some code but getting an exception.

The Exception that I'm getting: java.lang.IllegalArgumentException: Invalid document reference. Document references must have an even number of segments, but Users has 1

I searched for it, according to this, Document references must have an even number of segments like: Collection - document - Collection - document - Collection - document

Query for getting data from firestore:

String getIsNewUSer;
Firestore.instance.collection('Users').document(uid).get().then((DocumentSnapshot document){
       print("document_build:$document");
        setState(() {
         getIsNewUSer=document['IsNewUser'];
         print("getIsNewUSe:$getIsNewUSer");
        });

    });

Query for Updating data to the firestore:

Firestore.instance
            .collection('Users')
            .document(uid)
            .updateData({
              "IsNewUser":"1"
            }).then((result){
              print("new USer true");
            }).catchError((onError){
             print("onError");
            });

These code line at I'm getting above Exception.

initState:

 void initState()  {
    super.initState();
    this.uid = '';

FirebaseAuth.instance.currentUser().then((val){
      setState(() {
      this.uid= val.uid; 
       print("uid_init: $uid");
      });
   });

}

Am I doing wrong?????..

like image 386
Shruti Ramnandan Sharma Avatar asked Sep 24 '19 09:09

Shruti Ramnandan Sharma


People also ask

How do I delete data from firestore with Flutter?

To delete a file, first create a reference to that file. Then call the delete() method on that reference. await desertRef. delete();


1 Answers

Null safe code:

  • Get data:

    var collection = FirebaseFirestore.instance.collection('collection');
    var docSnapshot = await collection.doc('doc_id').get();
    Map<String, dynamic>? data = docSnapshot.data();
    
  • Set data:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection.add(someData);
    
  • Update data:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('foo_id') // <-- Doc ID where data should be updated.
        .update(newData);
    
  • Delete data:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('some_id') // <-- Doc ID to be deleted. 
        .delete();
    
like image 76
CopsOnRoad Avatar answered Sep 30 '22 07:09

CopsOnRoad