I receive json from api with string array. Then I set it to local variable with type List.
if (json['x'] is List) {
List<String> x = json['x'];
print(x);
}
When I run application, Chrome show me a warning: "Ignoring cast fail from JSArray to List"
What should I do with that?
- Angular 5.0.0-alpha+6
- Chrome 63.0.3239.132
- Dart VM version: 2.0.0-dev.32.0
JSON encodes all arrays as List<dynamic>
, since that is the specification.
If you want to cast something to List<String>
, you can't rely on just an implicit cast like you did in Dart 2. You must either use the real type:
List x = json['x'];
Or use the .cast
function:
var x = (json['x'] as List).cast<String>();
I realize that is more writing than before. You might want to look at JSON serialization package such as json_serializable
or built_value
if you don't like the boiler-plate around this.