在我的问题中,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 ×1