firebaseflutterdartfirebase-realtime-database

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.


Solution

  • 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);