简体   繁体   中英

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.

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

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?

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> . dynamicList has a static type of List<dynamic> but has an actual runtime type of List<int> (it's the same object as intList ). 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.

In the second example, dynamicList has a static type of List<dynamic> and an actual runtime type of 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. You therefore instead must cast each element individually, which is exactly what List.from and List.cast do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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