Home > Net >  How to check whether the field exists in Firebase, if it exists then print its value, if it does not
How to check whether the field exists in Firebase, if it exists then print its value, if it does not

Time:12-24

How to make a function check if Firebase has a first_name: John field, and if there is no first_name field at all, then return first_name: empty value.

below is a variable that takes the name from the query

late String userName;

  Future getuserData(userName) async {
    await FirebaseFirestore.instance
        .collection("users")
        .doc(user?.uid)
        .get()
        .then((value) => userName = value.data()?["first_name"]);
  }

CodePudding user response:

when your document contains the "first_name", trying to get it like this value.data()?["first_name"] will return it's value, otherwise it will not find it and return null, so you can simply set an alternative ( which is the empty value ) like this:

  Future getuserData(userName) async {
    await FirebaseFirestore.instance
        .collection("users")
        .doc(user?.uid)
        .get()
        .then((value) => userName = (value.data()?["first_name"]) ?? "");
  }

now after the getuserData() is called, the userName will be either the value from your database if it exists, otherwise it will be the alternative "" which is an empty value.

  • Related