dart 类型“String”不是API响应子模型中“index”的类型“int”的子类型

ruoxqz4g  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(131)

我正在尝试从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'],
        ),
      );
}

这是我的模型**旅行. 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,

    };
}

This my modelDestination.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,
      };
}

This my modelAcomodation.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
                }
            ]
        }
    ]
}
lokaqttq

lokaqttq1#

错误消息“String”不是“index”的“int”类型的子类型,通常在您尝试使用字符串作为索引从列表中访问项时出现,或者当您尝试将String分配给int变量时出现,反之亦然。
在您的例子中,您得到这个错误似乎是因为您试图解析到Acomodation类中的JSON响应具有一些String值,而这些值应该是int值,反之亦然。
我可以看到你的Acomodation类有一个id属性,它是一个int。然而,在JSON响应中,“id”值似乎是一个字符串。此外,还有其他字段,如rateNight,total,它们可能是数字(int或double),但来自响应的字符串。
如果您希望这些字段是数字值,请确保您的后端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模型进行比较。要避免此类错误,请确保两端的数据类型匹配。如果不行请给我回电

相关问题