I am trying to use a file containing JSON data to populate my app, but I have the following error:
In my app screen:
Class Future<dynamic> has no instance getter 'popularGames'
In debug console:
Unhandled Exception: type 'int' is not a subtype of type 'String'
E/flutter (23544): #0 new Game.fromJson (package:juego/src/data/game.dart:31:28)
And my code:
games.json
[
{
"id": "1234",
"ownerId": "1",
"name": "Dobble",
"editor": "Spot it",
"wished": 1,
},
{
"id": "2345",
"ownerId": "1",
"name": "Jungle Speed",
"editor": "Asmodee",
"wished": 1,
}
]
game.dart (line 31 is wished)
class Game {
late int id;
late int ownerId;
late String name;
late String editor;
late int wished;
}
Game.fromJson(Map<String, dynamic> json) {
id = int.parse(json['id']);
ownerId = int.parse(json['ownerId']);
name = json['name'];
editor = json['editor'];
wished = int.parse(json['wished']);
}
library.dart
class Library {
List<Game> allGames = [];
final List<Session> allSessions = [];
loadJsonData() async {
String jsonData = await rootBundle.loadString('lib/src/assets/json/games.json');
//setState(() {
allGames = json.decode(jsonData).map<Game>((dataPoint) => Game.fromJson(dataPoint)).toList();
//});
}
2
Answers
"wished" is already an int. No need to parse it. Either quote it, or remove
int.parse
In your
games.json
file to define int your should not put it inside "" .replace the code in your
games.json
file by this :and replace your
game.dart
with this code :