英文:
type 'String' is not a subtype of type 'int' of 'index' in API response sub model
问题
I see you're encountering an error when trying to display data from the submodel of TravelStatus.dart
. The error message is:
'String' is not a subtype of type 'int' of 'index'
This error typically occurs when you're trying to use a String value where an int is expected in your code. You'll need to check your code to ensure that you're using the correct data types in the right places.
If you have specific questions about how to resolve this issue, please feel free to ask.
英文:
i am trying to get data from API. This problem occurs when I try to display data from the submodel of TravelStatus.dart. And i getting error like this
'String' is not a subtype of type 'int' of 'index'
this is my code to get data
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()}');
}
}
this is 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'],
),
);
}
this my model 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,
};
}
this my model 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,
};
}
this my model 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,
};
}
and the log
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'
my JSON response
{
"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
}
]
}
]
}
答案1
得分: 1
以下是翻译好的部分:
错误消息“String”不是“int”的子类型的“index”通常在您尝试使用字符串作为索引访问列表中的项目时,或当您尝试将String分配给int变量或反之亦然时出现。
在您的情况下,看起来您之所以收到此错误是因为您尝试解析为您的Acomodation类的JSON响应中存在一些字符串值,其中期望为int值,或反之亦然。
我可以看到您的Acomodation类具有一个int属性id。但是,在JSON响应中,“id”值似乎是一个字符串。此外,您还有其他字段,例如rateNight、total,可能期望为数字(int或double),但从响应中获取的是字符串。
如果您期望这些字段的值为数字,请确保您的后端API将它们作为数字发送,而不是字符串。如果您无法控制后端API并且返回的值将始终是字符串,则需要修改您的模型类以反映这一点:
class Acomodation {
final String id; // 将类型从int更改为String
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"].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模型进行比较。为了避免此类错误,请确保数据类型在两端匹配。如果仍然不起作用,请与我联系。
英文:
The error message 'String' is not a subtype of type 'int' of 'index' typically arises when you're trying to access an item from a list using a string as an index, or when you are trying to assign a String to an int variable or vice versa.
In your case, it seems like you're getting this error because the JSON response that you're trying to parse into your Acomodation class has some String values where int values are expected, or vice versa.
I can see that your Acomodation class has an id attribute that is an int. However, in the JSON response, it seems like the "id" value is a string. Also, you have other fields like rateNight, total which might be expected to be numbers (int or double) but coming as String from the response.
If you are expecting numeric values for those fields, make sure your backend API sends them as numbers, not strings. If you have no control over the backend API and the returned values will always be String, then you need to modify your model class to reflect this:
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,
};
}
In this updated class, I changed the id from int to String and used json["id"].toString() in Accomodation.fromJson to make sure it is parsed as a string.
However, you should carefully check which fields are causing the problem in your particular case and set their types accordingly in your model class. Also, review your JSON response and compare it to your Dart models. To avoid such errors, make sure your data types match on both ends. If it doesn't work please get back to me
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论