【问题标题】:Difference between converting a list to a new type using List.from vs List.map?使用 List.from 与 List.map 将列表转换为新类型之间的区别?
【发布时间】:2020-07-17 02:55:15
【问题描述】:

假设我想将以下收藏转换为List<int>

final listDouble = <double>[1.0, 2.0];

我可以使用

final listInt = List<int>.from(listDouble);

final listInt = listDouble.map<int>((e) => e.toInt()).toList();

这两种方法有什么区别吗?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    除了iDecode's answer 提到的懒惰之外,您应该知道List&lt;E&gt;.from 方式在技术上并不适合您的情况。

    List&lt;E&gt;.from 要求参数列表具有E 类型的元素,而ints 不是doubles。 (请注意,它适用于 Web 平台(例如 DartPad),其中 Dart 被转译为 JavaScript,因为所有 JavaScript 数字都是 IEEE-754 双精度浮点数。但是,如果您在 Dart VM 中尝试它,它会抛出例外。)

    【讨论】:

    • 是的,你是对的,我应该将列表从double 转换为int,那样的话它会起作用,对吗?
    • @iKeepChangingName 从double 转换为intint 转换为double 都没有关系。两者都不是从另一个派生的,因此它们不能隐式转换。
    • 好的,在这种情况下,我想对你的行 List&lt;E&gt;.from requires that the argument list have elements of type E? 做更多解释
    • 我不知道该怎么解释了;它的意思正是它所说的。 List&lt;int&gt;.from 要求参数已经是 ints 的集合。 List&lt;int&gt;.fromList&lt;int&gt;.of 基本相同,除了 .from 来自 Dart 编译时类型检查之前,因此如果参数类型错误,.from 将在运行时失败。
    • 因为您的详细解释,我接受了您的回答。谢谢。你
    【解决方案2】:

    是的,有区别。

    map() 返回一个惰性Iterable,这意味着提供的函数仅在元素被迭代时才被调用,这与List.from() 不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多