在 DART 中 - toList() 方法不会将 int 的 Iterable 转换为列表,但是当它应用于 print() 内部时,它可以正常工作。为什么?

Sid*_*rma 3 oop mapping loops dart flutter

我创建了一个列表“数字”,然后使用“映射”方法对其进行循环并将输出分配给方块。现在我在“squares”上应用 toList() 方法将其转换为 List 类型,但在输出中它被打印为 int 的可迭代。但是,当我在 print() 方法中执行相同的操作时,它会以列表形式提供输出。那么为什么它在 print() 方法之外不起作用呢?

 void main() {
  const numbers = [1, 2, 3, 4];
  final squares = numbers.map((number) => number * number);
  squares.toList(); // I've applied toList() method here

  print(squares); // But I don't get a list from this output
  print(squares.toList()); // But I get it from this output. Why?

}
Run Code Online (Sandbox Code Playgroud)

输出 (1, 4, 9, 16) [1, 4, 9, 16]

bel*_*tas 5

toList()将数据转换为列表,但必须将结果分配给变量。例如:

List list = squares.toList();
Run Code Online (Sandbox Code Playgroud)

然后就可以使用新变量了。