How to check if value exists in Firebase Realtime Database (Dart/Flutter)?

Viewed 4394

How can I check if a certain value exists in a Firebase Realtime Database?

I am using the following command but it is not working:

Future<bool> rootFirebaseIsExists(DatabaseReference databaseReference) async{
  DataSnapshot snapshot = await databaseReference.once();
  if( snapshot == null ){
    print("Item doesn't exist in the db");
  }else{
    print("Item exists in the db");
  }
  return snapshot !=null;
}
print("exists?");
rootFirebaseIsExists(FirebaseDatabase.instance.reference().child("users").child('userid000').child('pushTokens').child("field_to_check"));

The problem is that even when the node doesn't exist the the snapshot is not null and then the function returns that the item exists in the db.

Thanks!

1 Answers

once() always yields a DataSnapshot object. You have to check if that snapshot contains any data by looking at its value property.

  if (snapshot.value == null) {
    print("Item doesn't exist in the db");
  } else {
    print("Item exists in the db");
  }
Related