将字符串列表转换为 int Dart 列表

TSR*_*TSR 10 dart

如何在没有 for 循环的情况下将列表从一种类型转换为另一种类型?

List <String> lstring = <String>["1", "2"];
List <int> lint = lstring.map(int.parse);
Run Code Online (Sandbox Code Playgroud)

我收到错误:

type 'MappedListIterable<String, int>' is not a subtype of type 'List<int>'
Run Code Online (Sandbox Code Playgroud)

hel*_*ach 17

您需要将toList()添加到第二行的末尾。

List <String> lstring = <String>["1", "2"];
List <int> lint = lstring.map(int.parse).toList();
Run Code Online (Sandbox Code Playgroud)

这将做到。

  • 大多数 Iterable 操作都是惰性的,只有在实际迭代结果时才执行,toList() 需要这样做来创建新列表。 (2认同)

小智 6

final List<String> lstring = ["1", "2"];
final List<int> newList = lstring.map((e)=>int.parse(e)).toList();
Run Code Online (Sandbox Code Playgroud)