thecode
thecode

Reputation: 87

Conditional Statement with Data from Firestore

I set up a cloud-firestore from firebase. Here I want to save if some Shop is a favorite from the user. Therefore I assigned each Shop a document favorite with the field-

"color:" "grey" or "color:" "red".

To change the value in firestore I access it with this if-statement:

if (Firestore.instance.collection("favorites")
    .document(user1')
    .collection('shops')
    .document("$index").toString() == "grey") {...}

This has no effect. The program immediately jumps to the else statement. In Firestore the document 0 looks like this :

color: "grey".

In this case 0 stands for the first shop. I applied the number 0 to it, so that I can access the shops via index.

I think it has to be something wrong with my if statement, the else function which changes the value in firestore, looks exactly the same, except the toString() == 'grey'.

else {Firestore.instance.runTransaction((transaction) async {
     await transaction.set(Firestore.instance.collection("favorites")
         .document('dd')
         .collection('shops')
         .document("$index"), {'color': 'grey',});
         });
 }

I do have the same problem with the conditional statement, with which I choose the color with the values in the field. With this I want to access firestore and look which value is applied to each shop:

Firestore.instance.collection('favorites')
    .document('dd')
    .collection("shops")
    .document("1").toString() == "grey" ? Colors.grey : Colors.red ,

The same problem here, it immediately jumps to the color red and every shop is marked as favorite.

Upvotes: 0

Views: 931

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

Queries to the Firestore database are asynchronous. So you if you do something like

Firestore.instance.collection('favorites')
.document('user1')
.collection('shops')
.document("$index").toString() == "grey"

it will always be false.

You have to do as explained in the doc, to wait that the promise returned by the get() method resolves:

Firestore.instance
    .collection("favorites")
    .document('user1')
    .collection('shops')
    .document("$index")
    .get()
    .then((DocumentSnapshot ds) {
       // use ds as a snapshot
        const docData = ds.data;
        const color = docData["color"];

        //Do whatever you want with color value

    });

For more details, see https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentSnapshot-class.html

Upvotes: 2

Related Questions