type 'String' 不是 API 响应子模型中 'index' 的 'int' 类型的子类型

type 'String' is not a subtype of type 'int' of 'index' in API response sub model

提问人:Ardabily 提问时间:6/12/2023 更新时间:6/12/2023 访问量:62

问:

我正在尝试从 API 获取数据。当我尝试显示 TravelStatus.dart 的子模型中的数据时,会出现此问题。我收到这样的错误

'String' is not a subtype of type 'int' of 'index'

这是我获取数据的代码

List<dynamic> travel = [];
getTravel() async {
    String token = await getToken();
    try {
      Uri url = Uri.parse('http://10.0.2.2:8000/api/travel');
      final http.Response response = await http.get(url, headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer $token'
      });
      DMethod.printResponse(response);
      travel = jsonDecode(response.body)['group']
          .map((e) => TravelStatus.fromJson(e))
          .toList();
      setState(() {});
    } catch (e) {
      print('terjadi kesalahan: ${e.toString()}');
    }
  }

这是 TravelStatus.dart

class TravelStatus {
  final int id;
  final String travelStatus;
  final int userId;
  final int currentuser;
  final DateTime createdAt;
  final DateTime updatedAt;
  final Travel travel;
  final Destination destination;
  final Acomodation acomodation;

  TravelStatus({
    required this.id,
    required this.travelStatus,
    required this.userId,
    required this.currentuser,
    required this.createdAt,
    required this.updatedAt,
    required this.travel,
    required this.destination,
    required this.acomodation,
  });

  factory TravelStatus.fromJson(Map<String, dynamic> json) => TravelStatus(
        id: json["id"],
        travelStatus: json["travel_status"],
        userId: json["user_id"],
        currentuser: json["current_user"],
        createdAt: DateTime.parse(json["created_at"]).toLocal(),
        updatedAt: DateTime.parse(json["updated_at"]).toLocal(),
        travel: Travel(
          id: json['travel']['id'],
          reason: json['travel']['reason'],
          description: json['travel']['description'],
          organizationUnit: json['travel']['organization_unit'],
          tripAdvance: json['travel']['trip_advance'],
          tripExpense: json['travel']['trip_expense'],
          totalAmount: json['travel']['total_amount'],
        ),
        destination: Destination(
          id: json['destination']['id'],
          destination: json['destination']['destination'],
          start: json['destination']['start'],
          end: json['destination']['end'],
          transType: json['destination']['trans_type'],
          tripAdv: json['destination']['trip_adv'],
          curencyAdv: json['destination']['curency_adv'],
          locationTripAdv: json['destination']['location_trip_adv'],
          curencyLocation: json['destination']['curency_location'],
          meal: json['destination']['meal'],
          mealCurency: json['destination']['meal_curency'],
        ),
        acomodation: Acomodation(
          id: json['acomodation']['id'],
          checkIn: json['acomodation']['check_in'],
          checkOut: json['acomodation']['check_out'],
          location: json['acomodation']['location'],
          hotel: json['acomodation']['hotel'],
          curency: json['acomodation']['curency'],
          rateNight: json['acomodation']['rate_night'],
          total: json['acomodation']['total'],
          remarks: json['acomodation']['remarks'],
          billToCompany: json['acomodation']['bill_to_company'],
          chargeCode: json['acomodation']['bill_to_company'],
        ),
      );
}

这是我的模型 Travel.dart

class Travel {
    final int id;
    final String reason;
    final String description;
    final String organizationUnit;
    final String tripAdvance;
    final String tripExpense;
    final String totalAmount;


    Travel({
        required this.id,
        required this.reason,
        required this.description,
        required this.organizationUnit,
        required this.tripAdvance,
        required this.tripExpense,
        required this.totalAmount,

    });

    factory Travel.fromJson(Map<String, dynamic> json) => Travel(
        id: json["id"],
        reason: json["reason"],
        description: json["description"],
        organizationUnit: json["organization_unit"],
        tripAdvance: json["trip_advance"],
        tripExpense: json["trip_expense"],
        totalAmount: json["total_amount"],

    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "reason": reason,
        "description": description,
        "organization_unit": organizationUnit,
        "trip_advance": tripAdvance,
        "trip_expense": tripExpense,
        "total_amount": totalAmount,

    };
}

这是我的模型 Destination.dart

class Destination {
  final int id;
  final String destination;
  final String start;
  final String end;
  final String transType;
  final String tripAdv;
  final String curencyAdv;
  final String locationTripAdv;
  final String curencyLocation;
  final String meal;
  final String mealCurency;

  Destination({
    required this.id,
    required this.destination,
    required this.start,
    required this.end,
    required this.transType,
    required this.tripAdv,
    required this.curencyAdv,
    required this.locationTripAdv,
    required this.curencyLocation,
    required this.meal,
    required this.mealCurency,
  });

  factory Destination.fromJson(Map<String, dynamic> json) => Destination(
        id: json["id"],
        destination: json["destination"],
        start: json["start"],
        end: json["end"],
        transType: json["trans_type"],
        tripAdv: json["trip_adv"],
        curencyAdv: json["curency_adv"],
        locationTripAdv: json["location_trip_adv"],
        curencyLocation: json["curency_location"],
        meal: json["meal"],
        mealCurency: json["meal_curency"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "destination": destination,
        "start": start,
        "end": end,
        "trans_type": transType,
        "trip_adv": tripAdv,
        "curency_adv": curencyAdv,
        "location_trip_adv": locationTripAdv,
        "curency_location": curencyLocation,
        "meal": meal,
        "meal_curency": mealCurency,
      };
}

这是我的模型 Acomodation.dart

class Acomodation {
  final int id;
  final String checkIn;
  final String checkOut;
  final String location;
  final String hotel;
  final String curency;
  final String rateNight;
  final String total;
  final String remarks;
  final String billToCompany;
  final String chargeCode;

  Acomodation({
    required this.id,
    required this.checkIn,
    required this.checkOut,
    required this.location,
    required this.hotel,
    required this.curency,
    required this.rateNight,
    required this.total,
    required this.remarks,
    required this.billToCompany,
    required this.chargeCode,
  });

  factory Acomodation.fromJson(Map<String, dynamic> json) => Acomodation(
        id: json["id"],
        checkIn: json["check_in"],
        checkOut: json["check_out"],
        location: json["location"],
        hotel: json["hotel"],
        curency: json["curency"],
        rateNight: json["rate_night"],
        total: json["total"],
        remarks: json["remarks"],
        billToCompany: json["bill_to_company"],
        chargeCode: json["charge_code"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "check_in": checkIn,
        "check_out": checkOut,
        "location": location,
        "hotel": hotel,
        "curency": curency,
        "rate_night": rateNight,
        "total": total,
        "remarks": remarks,
        "bill_to_company": billToCompany,
        "charge_code": chargeCode,
      };
}

日志

I/flutter (20850): Response: GET | http://10.0.2.2:8000/api/travel | 200
I/flutter (20850): {"group":[{"id":11,"travel_status":"Menunggu Persetujuan","user_id":0,"current_user":6,"created_at":"2023-06-12T03:05:53.000000Z","updated_at":"2023-06-12T03:05:53.000000Z","travel":[{"id":10,"document_date":null,"reason":"1","description":"1","organization_unit":"1","trip_advance":"1","trip_expense
I/flutter (20850): ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
I/flutter (20850): terjadi kesalahan: type 'String' is not a subtype of type 'int' of 'index'

我的 JSON 响应

{
    "group": [
        {
            "id": 11,
            "travel_status": "Menunggu Persetujuan",
            "user_id": 0,
            "current_user": 6,
            "created_at": "2023-06-12T03:05:53.000000Z",
            "updated_at": "2023-06-12T03:05:53.000000Z",
            "travel": [
                {
                    "id": 10,
                    "document_date": null,
                    "reason": "1",
                    "description": "1",
                    "organization_unit": "1",
                    "trip_advance": "1",
                    "trip_expense": "1",
                    "total_amount": "1",
                    "user_id": 6,
                    "travel_status_id": 11
                }
            ],
            "destination": [
                {
                    "id": 5,
                    "destination": "2",
                    "start": "2",
                    "end": "2",
                    "trans_type": "2",
                    "trip_adv": "2",
                    "curency_adv": "2",
                    "location_trip_adv": "2",
                    "curency_location": "2",
                    "meal": "2",
                    "meal_curency": "2",
                    "user_id": 6,
                    "travel_status_id": 11
                }
            ],
            "acomodation": [
                {
                    "id": 4,
                    "check_in": "3",
                    "check_out": "3",
                    "location": "3",
                    "hotel": "3",
                    "curency": "3",
                    "rate_night": "3",
                    "total": "3",
                    "remarks": "3",
                    "bill_to_company": "3",
                    "charge_code": "3",
                    "user_id": 6,
                    "travel_status_id": 11
                }
            ]
        },
        {
            "id": 12,
            "travel_status": "Disetujui",
            "user_id": 0,
            "current_user": 6,
            "created_at": "2023-06-12T08:45:11.000000Z",
            "updated_at": "2023-06-12T08:45:11.000000Z",
            "travel": [
                {
                    "id": 11,
                    "document_date": null,
                    "reason": "1",
                    "description": "1",
                    "organization_unit": "1",
                    "trip_advance": "1",
                    "trip_expense": "1",
                    "total_amount": "1",
                    "user_id": 6,
                    "travel_status_id": 12
                }
            ],
            "destination": [
                {
                    "id": 6,
                    "destination": "2",
                    "start": "2",
                    "end": "2",
                    "trans_type": "2",
                    "trip_adv": "2",
                    "curency_adv": "2",
                    "location_trip_adv": "2",
                    "curency_location": "2",
                    "meal": "2",
                    "meal_curency": "2",
                    "user_id": 6,
                    "travel_status_id": 12
                }
            ],
            "acomodation": [
                {
                    "id": 5,
                    "check_in": "3",
                    "check_out": "3",
                    "location": "3",
                    "hotel": "3",
                    "curency": "3",
                    "rate_night": "3",
                    "total": "3",
                    "remarks": "3",
                    "bill_to_company": "3",
                    "charge_code": "3",
                    "user_id": 6,
                    "travel_status_id": 12
                }
            ]
        }
    ]
}
json flutter api 飞镖

评论


答:

1赞 TheSylar 6/12/2023 #1

错误消息“String”不是“index”的“int”类型的子类型,通常出现在尝试使用字符串作为索引访问列表中的项目时,或者当您尝试将 String 分配给 int 变量时,反之亦然。

在您的例子中,您似乎收到此错误,因为您尝试解析到 Acomodation 类中的 JSON 响应具有一些 String 值,其中 int 值是预期的,反之亦然。

我可以看到您的 Acomodation 类有一个 id 属性,该属性是 int。但是,在 JSON 响应中,“id”值似乎是一个字符串。此外,您还有其他字段,例如 rateNight、total,它们可能是数字(int 或 double),但作为响应中的 String 出现。

如果您需要这些字段的数值,请确保后端 API 将它们作为数字而不是字符串发送。如果您无法控制后端 API,并且返回的值将始终为 String,则需要修改模型类以反映这一点:

class Acomodation {
  final String id;  // change type from int to String
  final String checkIn;
  final String checkOut;
  final String location;
  final String hotel;
  final String curency;
  final String rateNight;  // if these are numeric values, change the type
  final String total;  // if these are numeric values, change the type
  final String remarks;
  final String billToCompany;
  final String chargeCode;

  Acomodation({
    required this.id,
    required this.checkIn,
    required this.checkOut,
    required this.location,
    required this.hotel,
    required this.curency,
    required this.rateNight,
    required this.total,
    required this.remarks,
    required this.billToCompany,
    required this.chargeCode,
  });

  factory Acomodation.fromJson(Map<String, dynamic> json) => Acomodation(
        id: json["id"].toString(),
        checkIn: json["check_in"],
        checkOut: json["check_out"],
        location: json["location"],
        hotel: json["hotel"],
        curency: json["curency"],
        rateNight: json["rate_night"],
        total: json["total"],
        remarks: json["remarks"],
        billToCompany: json["bill_to_company"],
        chargeCode: json["charge_code"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "check_in": checkIn,
        "check_out": checkOut,
        "location": location,
        "hotel": hotel,
        "curency": curency,
        "rate_night": rateNight,
        "total": total,
        "remarks": remarks,
        "bill_to_company": billToCompany,
        "charge_code": chargeCode,
      };
}

在这个更新的类中,我将 id 从 int 更改为 String,并在 Accomodation.fromJson 中使用 json[“id”].toString() 来确保它被解析为字符串。

但是,在特定情况下,应仔细检查哪些字段导致了问题,并在模型类中相应地设置了它们的类型。此外,查看您的 JSON 响应并将其与 Dart 模型进行比较。为避免此类错误,请确保两端的数据类型匹配。如果它不起作用,请回复我

评论

0赞 Ardabily 6/13/2023
我已经尝试了您建议的解决方案,但仍然会出现同样的问题。我还检查了数据库,除 id 外,所有数据均采用字符串形式。
0赞 NotTheDr01ds 6/13/2023
你昨天的一些答案似乎可能完全或部分是由人工智能(例如,ChatGPT)编写的(另一个是NAA,不是答案)。请注意,此处禁止发布 AI 生成的内容。如果您使用 AI 工具来帮助回答任何答案,我鼓励您删除它。谢谢!
0赞 NotTheDr01ds 6/13/2023
读者应该仔细和批判性地审查这个答案,因为人工智能生成的信息通常包含根本性的错误和错误信息。如果您发现质量问题和/或有理由相信此答案是由 AI 生成的,请留下相应的反馈。审核团队可以使用您的帮助来识别质量问题。
0赞 TheSylar 6/13/2023
坦率地说,即使它是人工智能产生的,我也不会不检查它就扔在这里。请不要把我和别人混为一谈。有好的一天!