Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Map<String, dynamic> from Map<dynamic, dynamic> flutter

I have the code below :

 Map<dynamic, dynamic> result = snapshot.value;
 Map<String, dynamic> data = Map<String, dynamic>();
 for (dynamic type in result.keys) {
    data[type.toString()] = result[type];
 }
 print(data);
 print(data.runtimeType);

but data type is _InternalLinkedHashMap<String, dynamic> and i am not able to read its value, despite the ugly hack i have done above.

The direct cast also doesn't work : snapshot.value as Map<String, dynamic> throws the error : '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>'

I need to have a Map<String, dynamic> type to be able to create my custom class Object.

snapshot.value has a type of dynamic, but it's a json object that returns the result of a Realtime Database query and there is no documentation about how to retrieve the value into a Flutter object.

I have tried this answer but i can't use it as jsonDecode() takes a String as a parameter.

like image 262
Tom3652 Avatar asked Jul 12 '26 23:07

Tom3652


2 Answers

When I tried Tom's answer I got:

The argument type 'Object?' can't be assigned to the parameter type 'Map<dynamic, dynamic>'

To solve this, I had to do:

Map<String, dynamic>.from(snapshot.value as Map);

In fact, since all values in my database node are booleans, I was able to do this:

Map<String, bool>.from(snapshot.value as Map);
like image 178
Frank van Puffelen Avatar answered Jul 14 '26 14:07

Frank van Puffelen


This recent Firecast video solved my problem at 27min.

I also had an non explicit Flutter error about another nested HashMap in my data model object that could not be converted directly.

The solution is to use Map<String, dynamic>.from(snapshot.value) and this for every nested Map you have in your data model object

EDIT : See Frank's answer below that is the correct one for the latest version of the firebase_database package.

like image 26
Tom3652 Avatar answered Jul 14 '26 12:07

Tom3652



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!