Md. Kamrul Amin
Md. Kamrul Amin

Reputation: 2425

Firebase Database giving inconsistent data

I have a flutter app which is connected to firebase realtime database. I am getting inconsistent values from snapshot, everytime I am trying to retrieve data. Below is what my database looks like: database picture

Below is the flutter code, I am using to get all the users in a specific id:

new FutureBuilder(
  future: db.child("Users").orderByChild("_id").equalTo("$userId").once(),
  builder: (context, AsyncSnapshot<DataSnapshot> snapshot) {
    if (snapshot.hasData){
      final values = snapshot.data!.value;
      print("values: "+values.toString());
      return Text("userName: " + values.toString());
    }
    return CircularProgressIndicator();
    }
  ),

The values print statement gives the below result:

I/flutter (16745): values: [{phone: +880 (834) 473-3132, name: Luna Bray, _id: 615ec4d64259ae531dec9fcc}]
I/flutter (16745): values: {4: {phone: +880 (881) 491-2540, name: Sondra Paul, _id: 615ec4d6ee0c6d92626c1d55}}
I/flutter (16745): values: {3: {phone: +880 (973) 554-2796, name: Susan Walker, _id: 615ec4d60d00b15c0950e860}}
I/flutter (16745): values: {4: {phone: +880 (881) 491-2540, name: Sondra Paul, _id: 615ec4d6ee0c6d92626c1d55}}

As u can see from the print result, only the first print statement is a List and the others are Map. I need either the values from snapshot to be a list or a map. I just need the username of the id that matches the query. Any help is appreciated.

Upvotes: 1

Views: 183

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

You're seeing the result of the array coercion that Firebase's SDKs and REST API perform when they encounter sequential, numeric keys.

The best/most common solution is to not use sequential, numeric keys, but instead use Firebase's built-in push() operation to generate the keys for you. For many more reasons on why this is idiomatic, see this blog post: Best Practices: Arrays in Firebase.

If that is not an option for you, prefix the sequential, numeric keys with a short string, such as "key0", "key1", etc. This ensures that the SDK can't convert it to an array, and gives you a consistent map.

Upvotes: 1

Related Questions