在 DartPad 中运行以下代码时遇到类型错误。
void main() {
List<int> list = [10, 20, 30];
List<int> squares = list.map((x) => x * x);
squares.forEach((x) => print(x));
}
出现以下错误
Uncaught exception:
TypeError: Instance of 'MappedListIterable<int, int>':
type 'MappedListIterable<int, int>' is not a subtype of
type 'List<int>'
这里可能出了什么问题?
最佳答案
List<int> squares = list.map((x) => x * x);
需要
List<int> squares = list.map((x) => x * x).toList();
map()
返回一个 Iterable
,而不是 List
关于dart - 我在使用 list.map 函数时遇到类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54106654/