I am facing a strange error in flutter. I am using json serialisable.
Here is my code
class DivMatches{
final List<Match> matches;
DivMatches(this.matches);
factory DivMatches.fromJson(Map<String, dynamic> json) =>
_$DivMatchesFromJson(json);
Map<String, dynamic> toJson() => _$DivMatchesToJson(this);
}
My web api sends data like this
[
[
{..},
{..},
{..},
{..}
],
[...],
[...],
[...],
[...],
[...],
[...]
]
It's array of array.
Code that is generating error is
data = body.map((el) => DivMatches.fromJson(el)).toList();
error it gives
Exception has occurred.
_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')
Here is the screenshot
JSON DATA here is the screenshots of json data formate
Change this line :
final body = json.decode(res.body);
To this:
final body = json.decode(res.body) as List;
And this:
List<DivMatches> data = [];
body.forEach((el) {
final List<Match> sublist = el.map((val) => Match.fromJson(val)).toList();
data.add(DivMatches(sublist));
});
Note: check if your Match.fromJson returns a Match object or Map.
You can use cast<Type>()
:
import 'dart:convert';
void main() {
print(getScores());
}
class Score {
int score;
Score({this.score});
factory Score.fromJson(Map<String, dynamic> json) {
return Score(score: json['score']);
}
}
List<Score> getScores() {
var jsonString = '''
[
{"score": 40},
{"score": 80}
]
''';
List<Score> scores = jsonDecode(jsonString)
.map((item) => Score.fromJson(item))
.toList()
.cast<Score>(); // Solve Unhandled exception: type 'List<dynamic>' is not a subtype of type 'List<Score>'
return scores;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With