'Difference between casting with 'cast' method and 'as' keyword
What's the difference in Dart between casting with the as keyword and casting with the cast method?
See the following example:
import 'dart:convert';
class MyClass {
final int i;
final String s;
MyClass({required this.i, required this.s});
factory MyClass.fromJson(Map<String, dynamic> json) =>
MyClass(s: json["s"], i: json["i"]);
}
void main() {
const jsonString = '{"items": [{"i": 0, "s": "foo"}, {"i": 1, "s":"bar"}]}';
final json = jsonDecode(jsonString);
final List<MyClass> thisWorks = (json["items"] as List)
.cast<Map<String, dynamic>>()
.map(MyClass.fromJson)
.toList();
final List<MyClass> thisAlsoWorks = (json["items"] as List)
.map((json) => MyClass.fromJson(json as Map<String, dynamic>))
.toList();
final List<MyClass> thisCrashes =
(json['items'] as List<Map<String, dynamic>>)
.map(MyClass.fromJson)
.toList();
}
The last call (casting with as) results in an exception: type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>' in type cast.
I expected that casting with as would work like casting with the cast method without resulting in an exception.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
