I have a JSON response that I would like to parse to be able to use it's data. I have created the model accordingly using https://quicktype.io
/ which is given below. However, I believe I'm doing something wrong in my code which is the sole reason as to why I'm getting the below error. Any Ideas how I can parse the data and use it?
This is the response that I would like to work with(I specifically need the id at this point but would need to work with all in the future.):
{
"data": {
"id": "order_JHAkD14mNKjCsa",
"entity": "order",
"amount": 19200,
"amount_paid": 0,
"amount_due": 19200,
"currency": "INR",
"receipt": "1649488665",
"offer_id": null,
"status": "created",
"attempts": 0,
"notes": [],
"created_at": 1649488667
}
}
This is the Error I get:
E/flutter ( 8882): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
E/flutter ( 8882): Receiver: null
E/flutter ( 8882): Tried calling: map(Closure: (dynamic) => dynamic)
E/flutter ( 8882): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
E/flutter ( 8882): #1 new OrderId.fromJson
package:eatiano_app/…/orderId/orderIdModel.dart:52
E/flutter ( 8882): #2 orderIdFromJson
package:eatiano_app/…/orderId/orderIdModel.dart:8
E/flutter ( 8882): #3 OrderIdProvider.getOrderId
package:eatiano_app/…/orderId/orderIdProvider.dart:31
E/flutter ( 8882): <asynchronous suspension>
Here's the model Class(The lines against which the errors are pointed at are in the comments):
import 'package:meta/meta.dart';
import 'dart:convert';
OrderId orderIdFromJson(String str) => OrderId.fromJson(json.decode(str)); //Line 8
String orderIdToJson(OrderId data) => json.encode(data.toJson());
class OrderId {
OrderId({
required this.id,
required this.entity,
required this.amount,
required this.amountPaid,
required this.amountDue,
required this.currency,
required this.receipt,
required this.offerId,
required this.status,
required this.attempts,
required this.notes,
required this.createdAt,
});
final String id;
final String entity;
final int amount;
final int amountPaid;
final int amountDue;
final String currency;
final String receipt;
final dynamic offerId;
final String status;
final int attempts;
final List<dynamic> notes;
final int createdAt;
factory OrderId.fromJson(Map<String, dynamic> json) => OrderId(
id: json["id"],
entity: json["entity"],
amount: json["amount"],
amountPaid: json["amount_paid"],
amountDue: json["amount_due"],
currency: json["currency"],
receipt: json["receipt"],
offerId: json["offer_id"],
status: json["status"],
attempts: json["attempts"],
notes: List<dynamic>.from(json["notes"].map((x) => x)), //Line 52
createdAt: json["created_at"],
);
Map<String, dynamic> toJson() => {
"id": id,
"entity": entity,
"amount": amount,
"amount_paid": amountPaid,
"amount_due": amountDue,
"currency": currency,
"receipt": receipt,
"offer_id": offerId,
"status": status,
"attempts": attempts,
"notes": List<dynamic>.from(notes.map((x) => x)),
"created_at": createdAt,
};
}
This is the where I'm making the API call:
class OrderIdProvider with ChangeNotifier {
String baseUrl = '*****************************';
Map<String, dynamic> _orderId = {};
Map<String, dynamic> get orderId {
return {..._orderId};
}
Future<void> getOrderId(
String state,
// String couponCode,
String couponId,
) async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
final url = Uri.parse(baseUrl 'api/auth/order_id');
final response = await http.post(url, body: {
'state': state,
'coupon_code': couponId
}, headers: {
'Authorization': 'Bearer ${localStorage.getString('token')}',
'Accept': 'application/json'
});
// var res = response.body;
OrderId idOrder = orderIdFromJson(response.body); //Line 31
_orderId = idOrder.toJson();
print(_orderId[0]);
}
}
Any ideas what I would need to do to fix this?
CodePudding user response:
You can't call map value by index. The Map uses keys instead of indexes. Look at the example:
void main() {
Data data = Data(id: '100'); // <- map key is `ìd`
var map = data.toJson();
print(map["id"]); // 100
}
I don't see the main class in your example based on your JSON
example, like in my example Order
class.
Order orderFromJson(String str) => Order.fromJson(json.decode(str));
String orderToJson(Order data) => json.encode(data.toJson());
class Order {
Order({this.data});
Data? data;
factory Order.fromJson(Map<String, dynamic> json) => Order(
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data?.toJson(),
};
}
class Data {
Data({
this.id,
this.entity,
this.amount,
this.amountPaid,
this.amountDue,
this.currency,
this.receipt,
this.offerId,
this.status,
this.attempts,
this.notes,
this.createdAt,
});
String? id;
String? entity;
int? amount;
int? amountPaid;
int? amountDue;
String? currency;
String? receipt;
dynamic offerId;
String? status;
int? attempts;
List<dynamic>? notes;
int? createdAt;
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json["id"],
entity: json["entity"],
amount: json["amount"],
amountPaid: json["amount_paid"],
amountDue: json["amount_due"],
currency: json["currency"],
receipt: json["receipt"],
offerId: json["offer_id"],
status: json["status"],
attempts: json["attempts"],
notes: List<dynamic>.from(json["notes"].map((x) => x)),
createdAt: json["created_at"],
);
Map<String, dynamic> toJson() => {
"id": id,
"entity": entity,
"amount": amount,
"amount_paid": amountPaid,
"amount_due": amountDue,
"currency": currency,
"receipt": receipt,
"offer_id": offerId,
"status": status,
"attempts": attempts,
"notes": notes?.map((x) => x).toList(),
"created_at": createdAt,
};
}
And now you can get data in this way:
Order order = orderFromJson(response.body);
var map = order.toJson();
print(map["data"]);
CodePudding user response:
Try this replace your Line 31 to below one.
OrderId idOrder = orderIdFromJson(jsonDecode(response.body)["data"]); //Line 31
You facing this issue because respose.body hase string data type first you need to convert it into to the JSON by jsonDecode and then you can get your data