How to variable values comes from firestore database?

Issue

I’m using firestore database, this is my variables

  final firebase = FirebaseFirestore.instance;
  int lessonpoint1 = 0;
  int lessonpoint2 = 0;

I’ve created a metod to create these variables on startup

  create() async {
    try {
      await firebase.collection("Accounts").doc(_user.uid).set({
        "Adı Soyadı": _user.displayName,
        "Mail Adresi": _user.email,
        "lessonpoint1": lessonpoint1,
        "lessonpoint2": lessonpoint2,
      });
    } catch (e) {
      print(e);
    }
  }

after I create it, I don’t want the variables here to have a value of 0 here. I want to pull these values from firestore. How can I do that? I give the value 10 to the variable with Update, but when I want to access the variable, the value 0 at the global level comes.

Thank you,
have a good day.

Solution

Instead of directly setting the value from the client you could either use a Transaction or FieldValue.increment().

With a Transaction you would ensure that you always get the latest value from the database and update it on it.

With FieldValue.increment() it’s very similar but much less syntax and you can work inly with simple increments.

If you for example want to increase the points on each visit by 10 you could write your code like this:

create() async {
    try {
      await firebase.collection("Accounts").doc(_user.uid).set({
        "Adı Soyadı": _user.displayName,
        "Mail Adresi": _user.email,
        "lessonpoint1": FieldValue.increment(10),
        "lessonpoint2": FieldValue.increment(10),
      });
    } catch (e) {
      print(e);
    }
  }

If you are only interested how to get the data itself from firestore I would recommend to check out first the docu here.

You can read more about both the methods them here.

Answered By – Tarik Huber

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.