Home > Software engineering >  Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index
Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index

Time:07-02

Am getting a json response from server that looks like this

[
    {
        "player": {
            "id": 146,
            "is_cap": false,
            "average_skill": 5,
            "region": {
                "id": 13,
                "name_ar": "التجمع",
                "name_en": "El Tagamo3",
                "state": {
                    "id": 8,
                    "name_ar": "القاهره",
                    "name_en": "Cairo"
                }
            },
            "first_name": "shady",
            "last_name": "hussam",
            "mobile": "01020957753",
            "image": null,
            "positions_ar": [
                {
                    "دفاع شمال": 5
                },
                {
                    "مهاجم شمال": 5
                }
            ],
            "positions_en": [
                {
                    "LB": 5
                },
                {
                    "LF": 5
                }
            ],
            "basic_skills_ar": [
                {
                    "تسديد": 5
                },
                {
                    "السرعة": 5
                },
                {
                    "تمرير الكرة": 5
                }
            ],
            "basic_skills_en": [
                {
                    "shooting": 5
                },
                {
                    "speeding": 5
                },
                {
                    "Passing": 5
                }
            ]
        },
        "count": 1,
        "team": {
            "id": 74,
            "average_skill": "3.75",
            "points": 0,
            "name": "المنتقمون",
            "league": 31,
            "logo": "/uploads/6.png",
            "region_ar": "التجمع",
            "region_en": "El Tagamo3"
        }
    }
]

And am accessing it with a model that looks like this


class HomeTopScorer {
  int count;
  String teamLogo;
  String teamName;
  int id;
  bool isCap;
  int averageSkill;
  String region;
  String firstName;
  String lastName;
  String mobile;
  String image;
  List<String> positionsAr;
  List<String> positionsEn;
  List<String> basicSkillsAr;
  List<String> basicSkillsEn;

  HomeTopScorer({this.count,this.teamLogo,this.teamName,this.firstName,this.mobile,this.region,this.image,this.lastName,this.id,this.averageSkill,this.basicSkillsAr,this.basicSkillsEn,this.isCap,this.positionsAr,this.positionsEn});

After getting the response am trying to create a model using this function

  Future<dynamic> getHomeTopScorers() async {
    return await http.get(Uri.parse('my_url_is_used_here')).then((response) {
      if (response.statusCode == 401) {
        AuthHelpers().doLogout();
        Future.delayed(Duration(seconds: 1), () {
          Get.offAll(() => LoginView());
          Get.snackbar('please_login_again'.tr, '');
        });
      } else if (response.statusCode == 200) {
        final resp = jsonDecode(utf8.decode(response.bodyBytes));
        return resp;
      }
    });
  }

  getScorerList() {
    homeTopScorerProvider.getHomeTopScorers().then((resp) {
      print(resp); //Prints the right resp
      for (var single_item in resp){
        String theLogo = single_item['team']['logo']; //This is where the error happens
        HomeTopScorer newScorer = HomeTopScorer(count:single_item['count'],teamLogo:theLogo);
        print(newScorer.count);
        print(newScorer.teamLogo);
      }
      // homeTopScorerList.value = resp;
    });
  }

so this line String theLogo = single_item['team']['logo']; causes the following error

Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'

CodePudding user response:

It should be like this

 var data =jsonDecode(single_item);
  String theLogo = data ['team']['logo']; 

hope this will help you

CodePudding user response:

You can Use Quicktype.io to create a model then you will get something like this.

// To parse this JSON data, do
//
//     final homeTopScorer = homeTopScorerFromJson(jsonString);
import 'dart:convert';

List<HomeTopScorer> homeTopScorerFromJson(String str) => List<HomeTopScorer>.from(json.decode(str).map((x) => HomeTopScorer.fromJson(x)));

String homeTopScorerToJson(List<HomeTopScorer> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class HomeTopScorer {
    HomeTopScorer({
        this.player,
        this.count,
        this.team,
    });

    Player player;
    int count;
    Team team;

    factory HomeTopScorer.fromJson(Map<String, dynamic> json) => HomeTopScorer(
        player: Player.fromJson(json["player"]),
        count: json["count"],
        team: Team.fromJson(json["team"]),
    );

    Map<String, dynamic> toJson() => {
        "player": player.toJson(),
        "count": count,
        "team": team.toJson(),
    };
}

class Player {
    Player({
        this.id,
        this.isCap,
        this.averageSkill,
        this.region,
        this.firstName,
        this.lastName,
        this.mobile,
        this.image,
        this.positionsAr,
        this.positionsEn,
        this.basicSkillsAr,
        this.basicSkillsEn,
    });

    int id;
    bool isCap;
    int averageSkill;
    Region region;
    String firstName;
    String lastName;
    String mobile;
    dynamic image;
    List<Map<String, int>> positionsAr;
    List<PositionsEn> positionsEn;
    List<Map<String, int>> basicSkillsAr;
    List<BasicSkillsEn> basicSkillsEn;

    factory Player.fromJson(Map<String, dynamic> json) => Player(
        id: json["id"],
        isCap: json["is_cap"],
        averageSkill: json["average_skill"],
        region: Region.fromJson(json["region"]),
        firstName: json["first_name"],
        lastName: json["last_name"],
        mobile: json["mobile"],
        image: json["image"],
        positionsAr: List<Map<String, int>>.from(json["positions_ar"].map((x) => Map.from(x).map((k, v) => MapEntry<String, int>(k, v)))),
        positionsEn: List<PositionsEn>.from(json["positions_en"].map((x) => PositionsEn.fromJson(x))),
        basicSkillsAr: List<Map<String, int>>.from(json["basic_skills_ar"].map((x) => Map.from(x).map((k, v) => MapEntry<String, int>(k, v)))),
        basicSkillsEn: List<BasicSkillsEn>.from(json["basic_skills_en"].map((x) => BasicSkillsEn.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "is_cap": isCap,
        "average_skill": averageSkill,
        "region": region.toJson(),
        "first_name": firstName,
        "last_name": lastName,
        "mobile": mobile,
        "image": image,
        "positions_ar": List<dynamic>.from(positionsAr.map((x) => Map.from(x).map((k, v) => MapEntry<String, dynamic>(k, v)))),
        "positions_en": List<dynamic>.from(positionsEn.map((x) => x.toJson())),
        "basic_skills_ar": List<dynamic>.from(basicSkillsAr.map((x) => Map.from(x).map((k, v) => MapEntry<String, dynamic>(k, v)))),
        "basic_skills_en": List<dynamic>.from(basicSkillsEn.map((x) => x.toJson())),
    };
}

class BasicSkillsEn {
    BasicSkillsEn({
        this.shooting,
        this.speeding,
        this.passing,
    });

    int shooting;
    int speeding;
    int passing;

    factory BasicSkillsEn.fromJson(Map<String, dynamic> json) => BasicSkillsEn(
        shooting: json["shooting"] == null ? null : json["shooting"],
        speeding: json["speeding"] == null ? null : json["speeding"],
        passing: json["Passing"] == null ? null : json["Passing"],
    );

    Map<String, dynamic> toJson() => {
        "shooting": shooting == null ? null : shooting,
        "speeding": speeding == null ? null : speeding,
        "Passing": passing == null ? null : passing,
    };
}

class PositionsEn {
    PositionsEn({
        this.lb,
        this.lf,
    });

    int lb;
    int lf;

    factory PositionsEn.fromJson(Map<String, dynamic> json) => PositionsEn(
        lb: json["LB"] == null ? null : json["LB"],
        lf: json["LF"] == null ? null : json["LF"],
    );

    Map<String, dynamic> toJson() => {
        "LB": lb == null ? null : lb,
        "LF": lf == null ? null : lf,
    };
}

class Region {
    Region({
        this.id,
        this.nameAr,
        this.nameEn,
        this.state,
    });

    int id;
    String nameAr;
    String nameEn;
    Region state;

    factory Region.fromJson(Map<String, dynamic> json) => Region(
        id: json["id"],
        nameAr: json["name_ar"],
        nameEn: json["name_en"],
        state: json["state"] == null ? null : Region.fromJson(json["state"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "name_ar": nameAr,
        "name_en": nameEn,
        "state": state == null ? null : state.toJson(),
    };
}

class Team {
    Team({
        this.id,
        this.averageSkill,
        this.points,
        this.name,
        this.league,
        this.logo,
        this.regionAr,
        this.regionEn,
    });

    int id;
    String averageSkill;
    int points;
    String name;
    int league;
    String logo;
    String regionAr;
    String regionEn;

    factory Team.fromJson(Map<String, dynamic> json) => Team(
        id: json["id"],
        averageSkill: json["average_skill"],
        points: json["points"],
        name: json["name"],
        league: json["league"],
        logo: json["logo"],
        regionAr: json["region_ar"],
        regionEn: json["region_en"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "average_skill": averageSkill,
        "points": points,
        "name": name,
        "league": league,
        "logo": logo,
        "region_ar": regionAr,
        "region_en": regionEn,
    };
}
  • Related