How to set, get and update data to the cloud firestore in flutter?

让人想犯罪 __ 提交于 2020-12-13 03:46:08

问题


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?????..


回答1:


Replace this part in your queries:

Firestore.instance.collection('Users').document(uid)

with

Firestore.instance.document('Users/$uid')

Collection - document - Collection - document - Collection - document

Basically you already had the answer.




回答2:


It is possible that FirebaseAuth.instance.currentUser() future didn't complete and populte this.uid. So this.uid == '' (empty string). So Firestore is throwing errror as you are trying to updated document at Users which is a collection.

You can validate this by printing this.uid before the update statement.

One way is to use helper method to update

Future<void> update(Map data) async {
    final user = await FirebaseAuth.instance.currentUser();
    return Firestore.instance.collection('Users').document(user.uid).updateData(data);
}

Then you can use helpr method as update({isNewUser: "1"}).then((r) {...})....

You can follow same approach for fetching the document as well.



来源:https://stackoverflow.com/questions/58077155/how-to-set-get-and-update-data-to-the-cloud-firestore-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!