Handle string/int/null values safely in JSON parsing Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
52 lines
1.9 KiB
Dart
52 lines
1.9 KiB
Dart
class OrderHistoryItem {
|
|
final int orderId;
|
|
final String orderUuid;
|
|
final int businessId;
|
|
final String businessName;
|
|
final double total;
|
|
final int statusId;
|
|
final String statusName;
|
|
final int orderTypeId;
|
|
final String typeName;
|
|
final int itemCount;
|
|
final DateTime createdAt;
|
|
final DateTime? completedAt;
|
|
|
|
const OrderHistoryItem({
|
|
required this.orderId,
|
|
required this.orderUuid,
|
|
required this.businessId,
|
|
required this.businessName,
|
|
required this.total,
|
|
required this.statusId,
|
|
required this.statusName,
|
|
required this.orderTypeId,
|
|
required this.typeName,
|
|
required this.itemCount,
|
|
required this.createdAt,
|
|
this.completedAt,
|
|
});
|
|
|
|
factory OrderHistoryItem.fromJson(Map<String, dynamic> json) {
|
|
int parseId(dynamic val) => val is int ? val : int.tryParse(val.toString()) ?? 0;
|
|
double parseDouble(dynamic val) => val is num ? val.toDouble() : double.tryParse(val.toString()) ?? 0.0;
|
|
String parseStr(dynamic val) => val?.toString() ?? "";
|
|
|
|
return OrderHistoryItem(
|
|
orderId: parseId(json["OrderID"]),
|
|
orderUuid: parseStr(json["OrderUUID"]),
|
|
businessId: parseId(json["BusinessID"]),
|
|
businessName: parseStr(json["BusinessName"]).isEmpty ? "Unknown" : parseStr(json["BusinessName"]),
|
|
total: parseDouble(json["OrderTotal"]),
|
|
statusId: parseId(json["OrderStatusID"]),
|
|
statusName: parseStr(json["StatusName"]).isEmpty ? "Unknown" : parseStr(json["StatusName"]),
|
|
orderTypeId: parseId(json["OrderTypeID"]),
|
|
typeName: parseStr(json["TypeName"]).isEmpty ? "Unknown" : parseStr(json["TypeName"]),
|
|
itemCount: parseId(json["ItemCount"]),
|
|
createdAt: DateTime.tryParse(parseStr(json["CreatedAt"])) ?? DateTime.now(),
|
|
completedAt: parseStr(json["CompletedAt"]).isNotEmpty
|
|
? DateTime.tryParse(parseStr(json["CompletedAt"]))
|
|
: null,
|
|
);
|
|
}
|
|
}
|