问题
I want to cast a Map<String, dynamic>
to Map<String, List<String>>
.
I have tried the following in Flutter:
Map<String, dynamic> dynamicMap = {
'a': ['1', '2', '3'],
'b': ['1', '2', '3'],
'c': ['1', '2', '3'],
};
Map<String, List<String>> typedMap = dynamicMap;
But get the following error:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, List<String>>'
I then tried:
Map<String, List<String>> typedMap = dynamicMap.cast<String, List<String>>();
which seems to work initally, but you get the same error when trying to use it, such as print(typedMap)
.
Thanks for the help.
EDIT
It's worth mentioning that the following:
Map<String, dynamic> dynamicMap = {
'a': ['1', '2', '3'],
'b': ['1', '2', '3'],
'c': ['1', '2', '3'],
};
Map<String, List<String>> typedMap = dynamicMap.cast<String, List<String>>();
did in fact work (apologies for the mistake in the question).
However, when the data comes say from json like so:
String rawJson = """{
"a": ["1", "2", "3"],
"b": ["1", "2", "3"],
"c": ["1", "2", "3"]
}""";
final Map<String, dynamic> dynamicMapFromJson = json.decode(rawJson);
Map<String, List<String>> typedMap = dynamicMapFromJson.cast<String, List<String>>();
The code no longer works and raised the exception mentioned.
The answers below helped solve this problem.
回答1:
Map<String, dynamic> dynamicMap = {
'a': ['1', '2', '3'],
'b': ['1', '2', '3'],
'c': ['1', '2', '3'],
};
Map<String, List<String>> typedMap;
dynamicMap.forEach((key,value){
List<String> list = List.castFrom(value);
typedMap[key] = list
});
This is because a dynamic data type variable can be assigned with any of the data type at run time.
But values of typedMap here has been already declared with data type of List<String>
, nothing else can be assigned to it other than a List<String>
.
The error is because you're trying to asign a dynamic data type to a List<string>
data type, a pseudo example
String s = dynamic(); //impossible
dynamic s = String(); //possible
回答2:
Map method can help you to convert in your desire cast.
Check out follow code.
I also demonstrated how to access all value of map as a list. i hope this will work for you.
Map<String, dynamic> dynamicMap = {
'a': ['1', '2', '3'],
'b': ['1', '2', '3'],
'c': ['1', '2', '3'],
};
Map<String, List<String>> typedMap =
dynamicMap.map((key, value) => MapEntry(key, value));
typedMap.forEach((key, value) {
print(value[0]);
});
回答3:
I solution I ended up using and was most reliable was:
Map<String, List<String>> typedMap = dynamicMap.map(
(key, value) => MapEntry(key, List.castFrom(value))
);
Thanks @Viren V Varasadiya and @iamyadunandan for the help
来源:https://stackoverflow.com/questions/61014768/cast-mapstring-listdynamic-to-mapstring-liststring