简体   繁体   English

Dart:.toList() 和转换为 List 有什么区别

[英]Dart: What is the difference between .toList() and casting as List

Out of curiosity and after some research I did not find the same case as mine,出于好奇,经过一番研究,我没有找到和我一样的案例,

What is the difference between using the method .toList() and casting as List and when should each be used?使用方法.toList()和强制转换as List有什么区别,什么时候应该使用它们?

Kindly, consider providing an example.请考虑提供一个例子。

toList() is a method called on multiple types of objects and will gather all data from a data stream (or existing List ) and create a new List object containing the data. toList()是一种对多种类型的对象调用的方法,它将从数据 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ (或现有List )中收集所有数据,并创建一个包含数据的新 List object 。

as List is a way to tell a given object (often dynamic ) is in fact a List object on runtime. as List是一种告诉给定 object (通常是dynamic的)实际上是运行时的List object 的方法。 This is used if we cannot determined the type on compile type (eg if parsing JSON).如果我们无法确定编译类型的类型(例如,如果解析 JSON),则使用此选项。

Example例子

We decodes some JSON and tell Dart that we can guarantee that the type on runtime will be List by using as List .我们解码一些 JSON 并告诉 Dart 我们可以通过使用as List List

import 'dart:convert';

void main() {
  final list = json.decode('[1, 2, 3]') as List;
  print(list); // [1, 2, 3]

  final newList = list.cast<int>().map((e) => e * 2).toList();
  print(newList); // [2, 4, 6]
}

We then use .map to double each value and want to convert this into a new list by usin toList() .然后我们使用.map将每个值加倍,并希望通过使用toList()将其转换为新列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM