2
votes

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.

2

2 Answers

2
votes

I tested your code using DartPad:

void main() {
  //Custom json
  Map<dynamic, dynamic> json = {
    "window": {
      "title": "Sample Konfabulator Widget",
      "name": "main_window",
      "width": 500,
      "height": 500
    }
  };

  Map<dynamic, dynamic> result = json;
  Map<String, dynamic> data = Map<String, dynamic>();
  for (dynamic type in result.keys) {
    data[type.toString()] = result[type];
  }
  print(data);
  print(data['window']);
  print(data['window']['title']);
}

Print 1:

{window: {title: Sample Konfabulator Widget, name: main_window, width: 500, height: 500}}

Print 2:

{title: Sample Konfabulator Widget, name: main_window, width: 500, height: 500}

Print 3:

Sample Konfabulator Widget

I don't understand the problem

2
votes

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