skip to Main Content

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


  1. "wished" is already an int. No need to parse it. Either quote it, or remove int.parse

    Login or Signup to reply.
  2. In your games.json file to define int your should not put it inside "" .

    replace the code in your games.json file by this :

    [
        {
            "id": 1234,
            "ownerId": 1,
            "name": "Dobble",
            "editor": "Spot it",
            "wished": 1
        },
        {
            "id": 2345,
            "ownerId": 1,
            "name": "Jungle Speed",
            "editor": "Asmodee",
            "wished": 1
        }
    ]
    

    and replace your game.dart with this code :

    class Game{
      final int id;
      final int ownerId;
      final String name;
      final String editor;
      final int wished;
      const Game({
        required id,
        required ownerId,
        required name,
        required editor,
        required wished
      });
    
    
      factory Game.fromJson(Map<String, dynamic> json){
        return Game(
        id: json['id'],
        ownerId: json['ownerId'],
        name: json['name'],
        editor: json['editor'],
        wished: json['wished']
               );
             }
    
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search