简体   繁体   English

列表之间的区别<string> .from() 和列表<string>在 Dart</string></string>

[英]Difference between List<String>.from() and as List<String> in Dart

I have read a snapshot from Firebase, and am trying to extract the value from a node that is a list of strings.我已经从 Firebase 读取了一个快照,并试图从一个字符串列表的节点中提取值。

When I do this:当我这样做时:

List<String> answers = snapshot.value["answers"] as List<String>;

With the above I get a runtime error saying:有了上面我得到一个运行时错误说:

type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast类型'List<dynamic>'不是类型转换中类型'List<String>'的子类型

But somehow these two approaches below both work:但不知何故,下面这两种方法都有效:

List<String> answers = List<String>.from(snapshot.value["answers"])

Or this:或这个:

List<String> answers = snapshot.value["answers"].cast<String>()

What is the difference between the first and the other two constructs, and why can't I cast the List<dynamic> to a List<String> with the as casting operation?第一个和其他两个构造之间有什么区别,为什么我不能使用as转换操作将List<dynamic>转换为List<String>

Let's examine some examples:让我们来看看一些例子:

var intList = <int>[1, 2, 3];
var dynamicList = intList as List<dynamic>; // Works.
var intList2 = dynamicList as List<int>; // Works.

But:但:

var dynamicList = <dynamic>[1, 2, 3];
var intList = dynamicList as List<int>; // Fails at runtime.

What's the difference?有什么不同?

In the first example, intList has a static type of List<int> , and the actual runtime type of the object is also List<int> .在第一个示例中, intList的 static 类型为List<int> ,而 object 的实际运行时类型也是List<int> dynamicList has a static type of List<dynamic> but has an actual runtime type of List<int> (it's the same object as intList ). dynamicList具有List<dynamic>的 static 类型,但具有List<int>的实际运行时类型(与intList相同的 object )。 Since the object was originally a List<int> , it is impossible for the List object to hold anything but int elements, and casting back to List<int> is safe.由于 object 最初是List<int> ,因此List object 不可能保存除int元素之外的任何内容,并且转换回List<int>是安全的。

In the second example, dynamicList has a static type of List<dynamic> and an actual runtime type of List<dynamic> .在第二个示例中, dynamicList具有 List<dynamic> 的 static 类型和List<dynamic> List<dynamic>实际运行时类型。 Since the object is initially constructed as a List<dynamic> , non- int s elements could have been added to it, and casting to List<int> is not necessarily safe.由于 object 最初构造为List<dynamic> ,因此可能已将非int元素添加到其中,并且强制转换为List<int>不一定安全。 You therefore instead must cast each element individually, which is exactly what List.from and List.cast do.因此,您必须单独转换每个元素,这正是List.fromList.cast所做的。

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

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