Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart - how to convert Map<String, dynamic> to Map<String, String>

Tags:

dart

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> ?

like image 891
Jossef Harush Kadouri Avatar asked May 23 '20 16:05

Jossef Harush Kadouri


2 Answers

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()));
like image 130
Mattia Avatar answered Sep 17 '22 11:09

Mattia


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());

// ...
like image 25
Jossef Harush Kadouri Avatar answered Sep 20 '22 11:09

Jossef Harush Kadouri