Francesco Iapicca
Francesco Iapicca

Reputation: 2657

Parsing issue with Dart - [no build value ^ serializable ^ ]

Aye Aye good people,

[edited:

running this in dartpad

import 'dart:convert';
void main() {
  const String _json = '{"myListInt": [1]}';
  final Map<String, dynamic> _map = jsonDecode(_json);
  final List<int> _list = _map['myListInt'] as List<int>;
  _list.forEach((i) {
    String _s = i.toString();
    print(_s);
  });
}

returns

Uncaught exception:
CastError: Instance of 'JSArray': type 'JSArray' is not a subtype of type 
'List<int>'

in case I use

  final List<int> _list = List<int>.from(_map['myListInt'] as List<int>);

or

List<int>.generate(_map['myListInt'].length, (i)=>_map['myListInt'][i] as int);

returns

Uncaught exception:
Cannot read property 'length' of undefined

] what am I doing wrong?

Thank you in advance

Francesco

Upvotes: 0

Views: 47

Answers (2)

Francesco Iapicca
Francesco Iapicca

Reputation: 2657

ok, using ""as Iterable"" works,

import 'dart:convert';
void main() {
  const String _json = '{"myListInt": [1]}';
  final Map<String, dynamic> _map = jsonDecode(_json);
  final List<int> _list=  List<int>.from(_map['myListInt'] as Iterable);
  _list.forEach((i) {
    String _s = i.toString();
    print(_s);
  });
}

Upvotes: 0

Ryosuke
Ryosuke

Reputation: 3892

Instead of this line

myListInt: List<int>.from(_map['myListInt'] as List<int>),

you can use

myListInt: List<int>.generate(_map['myListInt'].length, (i)=>_map['myListInt'][i] as int 

Basically instead of casting the whole list, you have to cast each element one by one.

Upvotes: 1

Related Questions