19

This snippet compile successfully but fail in runtime

Map<String, dynamic> queryParameters = {"id": 3};
Map<String, String> stringQueryParameters = Map<String, String>.from(queryParameters);

Uncaught Error: TypeError: 3: type 'int' is not a subtype of type 'String'


What's the proper way to convert from Map<String, dynamic> to Map<String, String> ?

3 Answers 3

42

You can use .map to convert your keys:

  Map<String, dynamic> queryParameters = {"id": 3};
  Map<String, String> stringQueryParameters =
      queryParameters.map((key, value) => MapEntry(key, value?.toString()));
Sign up to request clarification or add additional context in comments.

2 Comments

Map<String, String> mapResult = queryParameters.map((key, value) => MapEntry(key, value != null ? value!.toString() : ''));
In my case, map() returns a Map<dynamic, dynamic>, which is also not a subtype of Map<String, String>.
6

Loop all items, call .toString() and store the result as the new value

Map<String, dynamic> queryParameters = {"id": 3, "name": null};
Map<String, String> stringQueryParameters = Map<String, String>();
queryParameters.forEach((key, value) => stringQueryParameters[key] = value?.toString());

// ...

Comments

0

@Mattia's answer didn't work for me. Calling map() returns a Map<dynamic, dynamic>, which is also not a subtype of Map<String, String>.

So in addition to calling map(), I found I needed to call cast().

Map<String, dynamic> queryParameters = {"id": 3};
Map<String, String> stringParameters = queryParameters.map(
  (key, value) => key, value?.toString())
).cast<String, String>();

Comments

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.