Flutter&Dart: How to convert the result to Map and dynamic isn't contained _JsonMap?

Viewed 41

My code looks like this:

RxMap<String, String> menuDrink = RxMap<String, String>({}), menuFood = RxMap<String, String>({});

Map<String, dynamic> result = {
  'balance': 100,
  'menu': {
    'drink': {
      '1': 'menu 1',
      '2': 'menu 2',
      '3': 'menu 3',
    },
    'food': {
      '1': 'menu 1',
      '2': 'menu 2',
      '3': 'menu 3',
    }
  }
};

menuDrink.value = result['menu']['drink'];
menuFood.value = result['menu']['food'];

This works fine. But when I get the result from

Map<String, dynamic> result = json.decode(response);

It will error:

Error: Expected a value of type 'Map<String, String>', but got one of type '_JsonMap'

I have tried

Map result = json.decode(response) as Map<String, dynamic>;

But this type is still _JsonMap.

For using

Map result = Map<String,dynamic>.from(json.decode(response));

I got the LinkedMap<dynamic, dynamic> type.

Or create a new Map:

Map resultFormatted = {};
for (MapEntry element in (result ?? {}).entries) {
  resultFormatted[element.key] = element.value;
}

The resultFormatted isn't _JsonMap now, but the Map value inside still _JsonMap.

How to convert the result to Map<String, dynamic> and dynamic isn't contained _JsonMap? Is it possible?

At the moment, I've created a function that converts the result['menu'][...] to Map<String,String>.

0 Answers
Related