Flutter Firebase Database, DataSnapshot? how to get values and keys, null safe

Issue

Using firebase_database: ^7.1.1

Before null safety i used to do like this to get the data from firebase database:

DataSnapshot dataSnapshot = await References.getReferenceYears().once();
Map<dynamic, dynamic> values = dataSnapshot.value;
values.forEach((key, value) {...}

Now when i try do like this, i get the error as bellow:

DataSnapshot? dataSnapshot = await References.getReferenceYears().once();
Map<dynamic, dynamic> values = dataSnapshot.value;

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type ‘List<Object?>’ is not a subtype of type ‘Map<dynamic, dynamic>’

I think this means that the keys are not being returned in the dataSnapshot.value, how can i use this now to get the (key, value) as before?

If I print the snapshot.value I get like this, so looks like the keys are no longer present in the snapshot.value as before, i don’t know where are the keys now:

[{name: 2016-2017}, {name: 2017-2018}, {name: 2018-2019}]

Thanks in advance.

Solution

It sounds like you have sequential, numeric keys under References.getReferenceYears(), which the SDK converts to an array. I don’t think this changed in a recent SDK, as Firebase always tries to coerce such keys into an array.

If you don’t want the values to be stored into an array, the easiest way to prevent that is to prefix the keys with a short non-numeric value, like:

"key_0": "value 0",
"key_1": "value 1",
"key_2": "value 2",
...

Answered By – Frank van Puffelen

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.