0

I try to assign a value to my Map<String, String> variable after I json-encode it and then json-decode it. The following code example is a simplified reproduce;

import 'dart:convert';

String toJson(dynamic object) {
  var encoder = new JsonEncoder.withIndent("     ");
  return encoder.convert(object);
}

dynamic fromJson(String jsonString) {
  return json.decode(jsonString);
}

void main() {
  Map<String, String> data = {"hello": "world"};
  String jsonString = toJson(data);
  data = fromJson(jsonString);
  print(data);
}

When I run it, it fails with;

Unhandled exception:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>'

And on this online editor it fails with a different error;

Uncaught exception:
TypeError: Instance of '_JsonMap': type '_JsonMap' is not a subtype of type 'Map<String, String>'

1 Answer 1

2

Workaround it,

I don't like it but it workaround the issue. Wrap the value returned by the fromJson function with Map<String, String>.from(...)

For example:

void main() {
  Map<String, String> data = {"hello": "world"};
  String jsonString = toJson(data);
  data = Map<String, String>.from(fromJson(jsonString));
  print(data);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Looks like type mismatch. It works if you replace Map<String, String> data = {"hello": "world"}; with Map<String, dynamic> data = {"hello": "world"};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.