繁体   English   中英

未处理的异常:类型'String'不是颤振中'index'的'int'类型的子类型

[英]Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' in flutter

我从服务器收到一个看起来像这样的 json 响应

[
    {
        "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"
        }
    }
]

并且正在使用看起来像这样的模型访问它


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});

得到响应后,我尝试使用此功能创建模型

  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;
    });
  }

所以这一行String theLogo = single_item['team']['logo']; 导致以下错误

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

你可以使用 Quicktype.io 创建一个模型然后你会得到这样的东西。

// 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,
    };
}

我建议你使用 app.quicktype.io 来创建模型类。 并从您的 json 转换为此并使用

最后的欢迎 = welcomeFromJson(jsonString);

import 'dart:convert';

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

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

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

Player player;
int count;
Team team;

factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
    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,
};
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM