在我的问题中,Dart 2.X List.cast()无法构成答案,因此需要将a转换List<dynamic>为a List<String>:
List<String> ls = (json['data'] as List).cast<String>().map((s) => s.toUpperCase()).toList();
Run Code Online (Sandbox Code Playgroud)
我从其他语言获得的经验让我首先写了这篇文章:
List<String> ls = (json['data'] as List<String>).map((s) => s.toUpperCase()).toList();
Run Code Online (Sandbox Code Playgroud)
请注意,这可以编译,但在Dart 2中运行时会失败。
为什么对Dart进行类型转换List需要一个功能as List).cast<String>(),而不是像Dart那样简单地使用as“类型转换运算符” as List<String>?
----编辑----
我正在使用最新的Dart 2.0.0-dev.43.0,并且在as类型转换/断言中出现不一致的运行时行为。是不是该.cast<>()函数创建一个新的迭代相同的.map()?将我的代码更改为此:
List<String> ls = (json['data'] as List).map((s) => (s as String).toUpperCase()).toList();
Run Code Online (Sandbox Code Playgroud)
这似乎是在利用第一个强制转换List为的优势List<dynamic>。因此,.map功能参数也是dynamic。
我上面的第二个示例to as List<String>可以在代码中的某些地方使用,而在其他地方则不能。请注意,IntelliJ可以正确推断上述所有示例中的类型-这是在运行时发生故障的地方。我猜这种不一致的行为是由于Dart 2.x仍在开发中。
---- 2nd编辑----
这是我的一个类构造函数中的测试用例:
Map<String, dynamic> json = { …Run Code Online (Sandbox Code Playgroud) 即将发布的 Dart 2.X 版本需要强类型。在处理 JSON 数据时,我们现在必须将dynamic类型转换为适当的 Dart 类型(不是问题)。一个相关的问题Ignoring cast fail from JSArray to List<String>提供了使用该.cast<String>()函数的答案。最近的一组消息也有同样的说法:
Breaking Change: --preview-dart-2 enabled by default。
问题是该.cast()函数似乎没有组合。使用 DDC 编译并在 Chrome 浏览器中运行时的原始代码:
Map<String, dynamic> json = { "data": ["a", "b", "c"] };
List<String> origBroken = json["data"].map( (s) => s.toUpperCase() ).toList();
Run Code Online (Sandbox Code Playgroud)
现在收到运行时警告(很快就会出错)
Ignoring cast fail from JSArray to List<String>
Run Code Online (Sandbox Code Playgroud)
所以我.cast<String>()按照文档和相关链接的建议添加,但仍然收到警告:
List<String> docFixBroken = json["data"].cast<String>().map( (s) => s.toUpperCase() ).toList();
List<String> alsoBroken = List.from( (json["data"] as List).cast<String>() ).map( (s) …Run Code Online (Sandbox Code Playgroud) dart ×2