强制转换"Map< String,List< dynamic>>"到"Map< String,List< String>>" [英] Cast "Map<String, List<dynamic>>" to "Map<String, List<String>>"

查看:84
本文介绍了强制转换"Map< String,List< dynamic>>"到"Map< String,List< String>>"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 Map< String,dynamic> 转换为 Map< String,List< String>> .

我已经在Flutter中尝试了以下方法:

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;

但是出现以下错误:

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, List<String>>'

然后我尝试:

Map<String, List<String>> typedMap = dynamicMap.cast<String, List<String>>();

这似乎可以正常工作,但是尝试使用它时会遇到相同的错误,例如 print(typedMap).

which seems to work initally, but you get the same error when trying to use it, such as print(typedMap).

感谢您的帮助.

值得一提的是以下内容:

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).

但是,当数据来自json时,就像这样:

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.

推荐答案

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

这是因为可以在运行时为动态数据类型变量分配任何数据类型.但是这里的typedMap值已经用 List< String> 的数据类型声明,除了 List< String> 之外,其他任何其他都不能赋给它.该错误是因为您试图将动态数据类型分配给 List< string> 数据类型(一个伪示例)

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

这篇关于强制转换"Map&lt; String,List&lt; dynamic&gt;&gt;"到"Map&lt; String,List&lt; String&gt;&gt;"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆