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>
?
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()));
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());
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With