JSON Loop flutter - flutter

I have trouble getting data from a complex json, below is the json in the request.i would like to display all comments under publication object
{
"code": 0,
"message": {
"message": "Détails de publication"
},
"publication": [
{
"id": 47,
"user_id": 4,
"name": "spadrilles",
"description": "deux spadrille presque neufs",
"category": "Bijoux",
"quantity": 0,
"size": "XS 32",
"brand": "ZARA",
"for_who": "homme",
"color": "Blanc",
"delivery": "disponible le 25-01-2020",
"price": "150.5",
"progression": 0,
"discount": "5",
"visibility": 0,
"status": "Presque Neuf",
"softdelete": 0,
"created_at": "2021-01-06T14:51:27.000000Z",
"updated_at": "2021-01-22T10:26:39.000000Z",
"picture1": "b7c992f0ac7b0edd7e7e5ee12e617d9c07411b4d343f64f1caf94aa08d08b8fc.jpg",
"picture2": "efdffb16f47e0ab40788b760ab9154fc95a1fded8f6963b227aceaff302e8623.png",
"picture3": "8e23d6ec620353c8802bb969836b5d80f6c871fdc419f695a7c1da0e71e378ff.png",
"picture4": null,
"picture5": "5f3eac05c317d25cd0d691d545236fb0ef6059870217ea50dfd45b914d997d82.png",
"comment": [
{
"id": 3,
"pub_id": 47,
"user_id": 21,
"comment": "test test testsssssssssssst",
"created_at": "2021-03-25T09:40:32.000000Z",
"updated_at": "2021-03-25T09:40:32.000000Z",
"username": "occasion_saly",
"user_picture": "1611217814.png"
},
{
"id": 4,
"pub_id": 47,
"user_id": 21,
"comment": "test test testsssssssssssst",
"created_at": "2021-03-25T09:40:36.000000Z",
"updated_at": "2021-03-25T09:40:36.000000Z",
"username": "occasion_saly",
"user_picture": "1611217814.png"
},
{
"id": 5,
"pub_id": 47,
"user_id": 21,
"comment": "test test testsssssssssssst",
"created_at": "2021-03-25T09:40:37.000000Z",
"updated_at": "2021-03-25T09:40:37.000000Z",
"username": "occasion_saly",
"user_picture": "1611217814.png"
}
],
"ownerpicture": "1608970983.png"
}
],
"error": {},
"status": 200
}
As you can see, under publication there are comment object and under those they have 3 comments.i want to display it all using for loop .
Kindly assist.
my code (usually dislay one comment):
#override
void initState() {
getproduct(widget.idproduct);
super.initState();
}
Future<dynamic> getproduct(int id) async {
var response = await Network().getData('/publication/show/$id');
data = json.decode(response.body)['publication'];
inspect(data);
return data;
}
child: SingleChildScrollView(
child: FutureBuilder(
future: getproduct(widget.idproduct),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
for (int i = 0; i < snapshot.data.length; i++)
CommentsList(
comment: snapshot.data[i]['comment'][i]
['comment'],
username: snapshot.data[i]['comment'][i]
['username'],
user_picture:
"${snapshot.data[i]['comment'][i]['user_picture']}",
)
],
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
),

Convert json to Your Entity and use it
You can use this site for Json to Dart code
Here code to convert json to Model
Response response=await http.get(url);
return YourDataEntity.fromJson(jsonDecode(resposne.body));
Here your entity
class YourDataEntity {
int code;
Message message;
List<Publication> publication;
Error error;
int status;
YourDataEntity({this.code, this.message, this.publication, this.error, this.status});
YourDataEntity.fromJson(Map<String, dynamic> json) {
code = json['code'];
message = json['message'] != null ? new Message.fromJson(json['message']) : null;
if (json['publication'] != null) {
publication = new List<Publication>();
json['publication'].forEach((v) { publication.add(new Publication.fromJson(v)); });
}
error = json['error'] != null ? new Error.fromJson(json['error']) : null;
status = json['status'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this.code;
if (this.message != null) {
data['message'] = this.message.toJson();
}
if (this.publication != null) {
data['publication'] = this.publication.map((v) => v.toJson()).toList();
}
if (this.error != null) {
data['error'] = this.error.toJson();
}
data['status'] = this.status;
return data;
}
}
class Message {
String message;
Message({this.message});
Message.fromJson(Map<String, dynamic> json) {
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['message'] = this.message;
return data;
}
}
class Publication {
int id;
int userId;
String name;
String description;
String category;
int quantity;
String size;
String brand;
String forWho;
String color;
String delivery;
String price;
int progression;
String discount;
int visibility;
String status;
int softdelete;
String createdAt;
String updatedAt;
String picture1;
String picture2;
String picture3;
Null picture4;
String picture5;
List<Comment> comment;
String ownerpicture;
Publication({this.id, this.userId, this.name, this.description, this.category, this.quantity, this.size, this.brand, this.forWho, this.color, this.delivery, this.price, this.progression, this.discount, this.visibility, this.status, this.softdelete, this.createdAt, this.updatedAt, this.picture1, this.picture2, this.picture3, this.picture4, this.picture5, this.comment, this.ownerpicture});
Publication.fromJson(Map<String, dynamic> json) {
id = json['id'];
userId = json['user_id'];
name = json['name'];
description = json['description'];
category = json['category'];
quantity = json['quantity'];
size = json['size'];
brand = json['brand'];
forWho = json['for_who'];
color = json['color'];
delivery = json['delivery'];
price = json['price'];
progression = json['progression'];
discount = json['discount'];
visibility = json['visibility'];
status = json['status'];
softdelete = json['softdelete'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
picture1 = json['picture1'];
picture2 = json['picture2'];
picture3 = json['picture3'];
picture4 = json['picture4'];
picture5 = json['picture5'];
if (json['comment'] != null) {
comment = new List<Comment>();
json['comment'].forEach((v) { comment.add(new Comment.fromJson(v)); });
}
ownerpicture = json['ownerpicture'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['user_id'] = this.userId;
data['name'] = this.name;
data['description'] = this.description;
data['category'] = this.category;
data['quantity'] = this.quantity;
data['size'] = this.size;
data['brand'] = this.brand;
data['for_who'] = this.forWho;
data['color'] = this.color;
data['delivery'] = this.delivery;
data['price'] = this.price;
data['progression'] = this.progression;
data['discount'] = this.discount;
data['visibility'] = this.visibility;
data['status'] = this.status;
data['softdelete'] = this.softdelete;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
data['picture1'] = this.picture1;
data['picture2'] = this.picture2;
data['picture3'] = this.picture3;
data['picture4'] = this.picture4;
data['picture5'] = this.picture5;
if (this.comment != null) {
data['comment'] = this.comment.map((v) => v.toJson()).toList();
}
data['ownerpicture'] = this.ownerpicture;
return data;
}
}
class Comment {
int id;
int pubId;
int userId;
String comment;
String createdAt;
String updatedAt;
String username;
String userPicture;
Comment({this.id, this.pubId, this.userId, this.comment, this.createdAt, this.updatedAt, this.username, this.userPicture});
Comment.fromJson(Map<String, dynamic> json) {
id = json['id'];
pubId = json['pub_id'];
userId = json['user_id'];
comment = json['comment'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
username = json['username'];
userPicture = json['user_picture'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['pub_id'] = this.pubId;
data['user_id'] = this.userId;
data['comment'] = this.comment;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
data['username'] = this.username;
data['user_picture'] = this.userPicture;
return data;
}
}
class Error {
Error();
// The response for error field is unclear
}

Related

http request get method is returning null in flutter

in my flutter app I'm using API request from server with http get method. but the response is returning null while printing the data inside the request it has data. how can I make an API call the right way?
JSON data
{
"client": [
{
"id": 1,
"name": "Muhammed",
"address": "Mexico",
"tin_no": "123456789",
"status": "1",
"created_at": "2022-09-09T08:44:18.000000Z",
"updated_at": "2022-09-09T08:44:18.000000Z",
"phones": [
{
"id": 2,
"client_id": "1",
"supplier_id": null,
"company_id": null,
"phone_number": "0911112222",
"email": "client#com.com",
"model": "Client",
"category": null,
"created_at": "2022-09-09T08:44:18.000000Z",
"updated_at": "2022-09-09T08:44:18.000000Z"
}
]
},
{
"id": 2,
"name": "Salem",
"address": "Torhailouch",
"tin_no": "87654321",
"status": "1",
"created_at": "2022-09-10T05:54:47.000000Z",
"updated_at": "2022-09-10T05:54:47.000000Z",
"phones": [
{
"id": 3,
"client_id": "2",
"supplier_id": null,
"company_id": null,
"phone_number": "0944551122",
"email": "client#com.com",
"model": "Client",
"category": "Sales",
"created_at": "2022-09-10T05:54:47.000000Z",
"updated_at": "2022-09-10T05:54:47.000000Z"
}
]
},]
}
Client model
class Client {
List<Clients>? clients;
Client({required this.clients});
Client.fromJson(Map<String, dynamic> json) {
if (json['clients'] != null) {
clients = <Clients>[];
json['clients'].forEach((v) {
clients?.add(new Clients.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.clients != null) {
data['clients'] = this.clients!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Clients {
int? id;
String? name;
String? address;
String? tinNo;
String? status;
String? createdAt;
String? updatedAt;
List<Phones>? phones;
Clients(
{this.id,
this.name,
this.address,
this.tinNo,
this.status,
this.createdAt,
this.updatedAt,
this.phones});
Clients.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
address = json['address'];
tinNo = json['tin_no'];
status = json['status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
if (json['phones'] != null) {
phones = <Phones>[];
json['phones'].forEach((v) {
phones!.add(new Phones.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['address'] = this.address;
data['tin_no'] = this.tinNo;
data['status'] = this.status;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.phones != null) {
data['phones'] = this.phones!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Phones {
int? id;
String? clientId;
Null? supplierId;
Null? companyId;
String? phoneNumber;
String? email;
String? model;
String? category;
String? createdAt;
String? updatedAt;
Phones(
{this.id,
this.clientId,
this.supplierId,
this.companyId,
this.phoneNumber,
this.email,
this.model,
this.category,
this.createdAt,
this.updatedAt});
Phones.fromJson(Map<String, dynamic> json) {
id = json['id'];
clientId = json['client_id'];
supplierId = json['supplier_id'];
companyId = json['company_id'];
phoneNumber = json['phone_number'];
email = json['email'];
model = json['model'];
category = json['category'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['client_id'] = this.clientId;
data['supplier_id'] = this.supplierId;
data['company_id'] = this.companyId;
data['phone_number'] = this.phoneNumber;
data['email'] = this.email;
data['model'] = this.model;
data['category'] = this.category;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
API call is as follows
Future<List<Client>> fetchClient() async {
Uri url = Uri.parse("${BASE_URL}client");
var response = await http.get(url, headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $TOKEN',
});
var data = json.decode(response.body);
print('...................$data...................');
List<Client> clients = [];
if (response.statusCode == 200) {
for (var singleClient in data) {
Client client = Client(clients: singleClient['clients']);
clients.add(client);
}
}
return clients;
}
main page
return FutureBuilder<List<Client>>(
future: fetchClient(),
builder: (context, AsyncSnapshot snapshot) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Text(index.toString());
});
});
Error thrown for this
Another exception was thrown: NoSuchMethodError: The getter 'length' was called on null.
what is the problem and how can I solve this?
Change your fetchClient() to this:
Future<List<Clients>> fetchClient() async {
Uri url = Uri.parse("${BASE_URL}client");
var response = await http.get(url, headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $TOKEN',
});
var data = json.decode(response.body);
print('...................$data...................');
List<Clients> clients = [];
if (response.statusCode == 200) {
for (var singleClient in data["client"]) {
clients.add(Clients.fromJson(singleClient));
}
}
return clients;
}
and also in your FutureBuilder do this:
return FutureBuilder<List<Clients>>(
future: fetchClient(),
builder: (context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const CircularProgressIndicator();
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List<Clients> data = snapshot.data;
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return Text(data[index].name);
});
});
}
}
});
You need to check in your builder whether the data is finished loading. something like
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Text(index.toString());
});
} else {
return const CircularProgressIndicator();
}

http 'POST' using an array not working properly in flutter

I've created an array of list of objects along with strings. and in my API i tried to use post method. the post method writes on the server but when i try to read the value with my model it throws an error of Unhandled Exception: NoSuchMethodError: Class 'bool' has no instance method 'forEach'.. I'm using a complex JSON structure.
Model class
class Client {
List<Clients>? clients;
Client({required this.clients});
Client.fromJson(Map<String, dynamic> json) {
if (json['clients'] != null) {
clients = <Clients>[];
json['clients'].forEach((v) {
clients?.add(new Clients.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.clients != null) {
data['clients'] = this.clients!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Clients {
int? id;
String? name;
String? address;
String? tinNo;
String? status;
String? createdAt;
String? updatedAt;
List<Phones>? phones;
Clients(
{this.id,
this.name,
this.address,
this.tinNo,
this.status,
this.createdAt,
this.updatedAt,
this.phones});
Clients.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
address = json['address'];
tinNo = json['tin_no'];
status = json['status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
if (json['phones'] != null) {
phones = <Phones>[];
json['phones'].forEach((v) {
phones!.add(new Phones.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['address'] = this.address;
data['tin_no'] = this.tinNo;
data['status'] = this.status;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.phones != null) {
data['phones'] = this.phones!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Phones {
int? id;
String? clientId;
Null? supplierId;
Null? companyId;
String? phoneNumber;
String? email;
String? model;
String? category;
String? createdAt;
String? updatedAt;
Phones(
{this.id,
this.clientId,
this.supplierId,
this.companyId,
this.phoneNumber,
this.email,
this.model,
this.category,
this.createdAt,
this.updatedAt});
Phones.fromJson(Map<String, dynamic> json) {
id = json['id'];
clientId = json['client_id'];
supplierId = json['supplier_id'];
companyId = json['company_id'];
phoneNumber = json['phone_number'];
email = json['email'];
model = json['model'];
category = json['category'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['client_id'] = this.clientId;
data['supplier_id'] = this.supplierId;
data['company_id'] = this.companyId;
data['phone_number'] = this.phoneNumber;
data['email'] = this.email;
data['model'] = this.model;
data['category'] = this.category;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
and my API call
Future createClient(String name, String address, String tin_no, String status,
List<Phones> phones) async {
Uri url = Uri.parse("${BASE_URL}client");
ClientController clientController = Get.put(ClientController());
final response = await http
.post(url,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $TOKEN',
},
body: jsonEncode(<String, dynamic>{
'name': name,
'address': address,
'tin_no': tin_no,
'status': status,
'phones': phones.toList()
}))
.then((value) {
if (value.statusCode == 200) {
clientController.setclientPress(true);
print(Clients.fromJson(json.decode(value.body)));
clientController.createClient(Clients.fromJson(json.decode(value.body)));
Get.back();
clientController.setclientPress(false);
print("success");
} else if (value.statusCode == 500) {
Get.snackbar("Data Exists", "The data you provided already exists.");
} else {
print("failed ${value.body}");
print("...............$phones");
}
print(value.body);
});
}
button for calling
onPressed: () async {
List<Phones> phones = [];
for (int i = 0; i < _groupControllers.length; i++) {
String _phone = _groupControllers[i].phone.text;
String _email = _groupControllers[i].email.text;
String _category = "Reception";
//_groupControllers[i].selectedCatagory.toString();
setState(() {
phones.add(Phones(
phoneNumber: _phone,
email: _email,
category: _category));
});
}
if (_formKey.currentState!.validate()) {
await createClient(
nameController.text,
addressController.text,
tinController.text,
idx.toString(),
phones);
}
}
response is
{
"client": {
"name": "trerw",
"address": "trwrte",
"tin_no": "45363524",
"status": "1",
"updated_at": "2022-10-01T12:44:19.000000Z",
"created_at": "2022-10-01T12:44:19.000000Z",
"id": 34
},
"phones": true,
"message": "Client created successfully"
}
the phones should not return bool. it should be as follows
{
"client": {
"id": 1,
"name": "Muhammed",
"address": "Mexico",
"tin_no": "123456789",
"status": "1",
"created_at": "2022-09-09T08:44:18.000000Z",
"updated_at": "2022-09-09T08:44:18.000000Z",
"phones": [
{
"id": 2,
"client_id": "1",
"supplier_id": null,
"company_id": null,
"phone_number": "0911112222",
"email": "client#com.com",
"model": "Client",
"category": null,
"created_at": "2022-09-09T08:44:18.000000Z",
"updated_at": "2022-09-09T08:44:18.000000Z"
}
]
}
}
what am i doing wrong?
As you can see in your api response:
{"client":{"name":"trerw","address":"trwrte","tin_no":"45363524","status":"1","updated_at":"2022-10-01T12:44:19.000000Z","created_at":"2022-10-01T12:44:19.000000Z","id":34},"phones":true,"message":"Client created successfully"}
phones is a bool variable, but in Clients.fromJson you consider it as list.So i think you send phones wrong in your api response.
Also you are passing phones in a wrong way to api body, try this:
body: jsonEncode(<String, dynamic>{
'name': name,
'address': address,
'tin_no': tin_no,
'status': status,
'phones': phones.map((e) => e.toJson()).toList();
}))

How can I get api Map data in my App SinglePage - Flutter

I need some help , How can I get SinglePage data from Api .
When I trying to get data show me this error : type '(dynamic) => ProductOrderModel' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'.
I hope I can find a solution from here. I am soo tired to get data.
Thanks...................
This is my controller :
class ProductOrderController extends GetxController {
getProductOrderDetails() async {
final sharedPreferences = await SharedPreferences.getInstance();
var token = sharedPreferences.getString('accessToken');
//
final res = await dio.get(baseUrl + 'customer/order/invoice/9',
options: Options(
headers: {'Authorization': 'Bearer $token'},
));
final List<ProductOrderModel> orderDetailsData = res.data
.map((json) => ProductOrderModel.fromJson(json))
.toList()
.cast<ProductOrderModel>();
print('------------------------------>');
print('Status Code : ${res.statusCode}');
print('Headers : ${res.headers}');
print('realUri : ${res.realUri}');
print('statusMessage : ${res.statusMessage}');
print('Category Data : $orderDetailsData');
print('requestOptions : ${res.requestOptions}');
// print(res.body);
// print(res.unauthorized);
print('------------------------------>');
orderDetailsData.addAll(orderDetailsData);
print(orderDetailsData);
}}
My Api Is :
{
"orderInfo": {
"orderIdPrimary": 9,
"customerId": "15",
"shippingId": "9",
"orderTotal": "930.00",
"discount": "0",
"bkashFee": "0",
"trackingId": "215707",
"orderStatus": "1",
"deliveryman_id": null,
"cancelRequest": "0",
"point": "9.15",
"pointamount": "0.00",
"created_at": "17-02-2022",
"updated_at": "2022-02-17T12:20:43.000000Z",
"ordertype": {
"id": 1,
"name": "Accepted",
"slug": "accepted",
"created_at": null,
"updated_at": null
},
"customer": {
"id": 15,
"fullName": "Fsd Ramjan",
"phoneNumber": "01779565300",
"address": null,
"email": null,
"verifyToken": "1",
"passResetToken": null,
"image": "public/uploads/avatar/avatar.png",
"provider": null,
"provider_id": null,
"point": "0.00",
"status": "1",
"created_at": "2022-02-16T11:00:40.000000Z",
"updated_at": "2022-02-19T03:23:33.000000Z"
},
"orderdetails": [
{
"orderDetails": "12",
"orderId": "9",
"ProductId": "2",
"productName": "Nestle LACTOGEN 2 Follow up Formula With Iron (6 months+) TIN",
"productSize": "",
"productColor": "",
"productPrice": "630.00",
"proPurchaseprice": "500",
"productQuantity": "1",
"created_at": "2022-02-17T12:20:43.000000Z",
"updated_at": "2022-02-17T12:20:43.000000Z",
"image": {
"id": 5,
"product_id": "2",
"image": "public/uploads/product/1644645502-1644066476-0129980_khusboo-premium-olive-pickles-400-gm.jpeg",
"created_at": "2022-02-12T05:58:22.000000Z",
"updated_at": "2022-02-12T05:58:22.000000Z"
}
},
{
"orderDetails": "13",
"orderId": "9",
"ProductId": "5",
"productName": "radhuni faluda mix",
"productSize": "",
"productColor": "",
"productPrice": "95.00",
"proPurchaseprice": "70",
"productQuantity": "3",
"created_at": "2022-02-17T12:20:43.000000Z",
"updated_at": "2022-02-17T12:20:43.000000Z",
"image": {
"id": 9,
"product_id": "5",
"image": "public/uploads/product/1644835159-pran-hot-tomato-sauce-340gm.jpg",
"created_at": "2022-02-14T10:39:19.000000Z",
"updated_at": "2022-02-14T10:39:19.000000Z"
}
}
],
"payment": {
"paymentIdPrimary": "9",
"orderId": "9",
"paymentType": "cod",
"senderId": null,
"transectionId": null,
"paymentStatus": "pending",
"bkashFee": null,
"created_at": "2022-02-17T12:20:43.000000Z",
"updated_at": "2022-02-17T12:20:43.000000Z"
},
"shipping": {
"shippingPrimariId": "9",
"customerId": "15",
"name": "Fsd Ramjan",
"phone": "01779565300",
"address": "jksrfjsdf",
"district": "9",
"area": "Munshiganj Sadar Upazila",
"shippingfee": "15",
"note": "fdfdf",
"created_at": "2022-02-17T12:20:43.000000Z",
"updated_at": "2022-02-17T12:20:43.000000Z"
}
}
}
I want to show this data in my app.
This is my model class generate from https://javiercbk.github.io
Model class :
class OderDetailsModel {
OrderInfo? orderInfo;
OderDetailsModel({this.orderInfo});
OderDetailsModel.fromJson(Map<String, dynamic> json) {
orderInfo = json['orderInfo'] != null
? new OrderInfo.fromJson(json['orderInfo'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.orderInfo != null) {
data['orderInfo'] = this.orderInfo!.toJson();
}
return data;
}
}
class OrderInfo {
int? orderIdPrimary;
String? customerId;
String? shippingId;
String? orderTotal;
String? discount;
String? bkashFee;
String? trackingId;
String? orderStatus;
Null? deliverymanId;
String? cancelRequest;
String? point;
String? pointamount;
String? createdAt;
String? updatedAt;
Ordertype? ordertype;
Customer? customer;
List<Orderdetails>? orderdetails;
Payment? payment;
Shipping? shipping;
OrderInfo(
{this.orderIdPrimary,
this.customerId,
this.shippingId,
this.orderTotal,
this.discount,
this.bkashFee,
this.trackingId,
this.orderStatus,
this.deliverymanId,
this.cancelRequest,
this.point,
this.pointamount,
this.createdAt,
this.updatedAt,
this.ordertype,
this.customer,
this.orderdetails,
this.payment,
this.shipping});
OrderInfo.fromJson(Map<String, dynamic> json) {
orderIdPrimary = json['orderIdPrimary'];
customerId = json['customerId'];
shippingId = json['shippingId'];
orderTotal = json['orderTotal'];
discount = json['discount'];
bkashFee = json['bkashFee'];
trackingId = json['trackingId'];
orderStatus = json['orderStatus'];
deliverymanId = json['deliveryman_id'];
cancelRequest = json['cancelRequest'];
point = json['point'];
pointamount = json['pointamount'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
ordertype = json['ordertype'] != null
? new Ordertype.fromJson(json['ordertype'])
: null;
customer = json['customer'] != null
? new Customer.fromJson(json['customer'])
: null;
if (json['orderdetails'] != null) {
orderdetails = <Orderdetails>[];
json['orderdetails'].forEach((v) {
orderdetails!.add(new Orderdetails.fromJson(v));
});
}
payment =
json['payment'] != null ? new Payment.fromJson(json['payment']) : null;
shipping = json['shipping'] != null
? new Shipping.fromJson(json['shipping'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['orderIdPrimary'] = this.orderIdPrimary;
data['customerId'] = this.customerId;
data['shippingId'] = this.shippingId;
data['orderTotal'] = this.orderTotal;
data['discount'] = this.discount;
data['bkashFee'] = this.bkashFee;
data['trackingId'] = this.trackingId;
data['orderStatus'] = this.orderStatus;
data['deliveryman_id'] = this.deliverymanId;
data['cancelRequest'] = this.cancelRequest;
data['point'] = this.point;
data['pointamount'] = this.pointamount;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.ordertype != null) {
data['ordertype'] = this.ordertype!.toJson();
}
if (this.customer != null) {
data['customer'] = this.customer!.toJson();
}
if (this.orderdetails != null) {
data['orderdetails'] = this.orderdetails!.map((v) => v.toJson()).toList();
}
if (this.payment != null) {
data['payment'] = this.payment!.toJson();
}
if (this.shipping != null) {
data['shipping'] = this.shipping!.toJson();
}
return data;
}
}
class Ordertype {
int? id;
String? name;
String? slug;
Null? createdAt;
Null? updatedAt;
Ordertype({this.id, this.name, this.slug, this.createdAt, this.updatedAt});
Ordertype.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
slug = json['slug'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['slug'] = this.slug;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
class Customer {
int? id;
String? fullName;
String? phoneNumber;
Null? address;
Null? email;
String? verifyToken;
Null? passResetToken;
String? image;
Null? provider;
Null? providerId;
String? point;
String? status;
String? createdAt;
String? updatedAt;
Customer(
{this.id,
this.fullName,
this.phoneNumber,
this.address,
this.email,
this.verifyToken,
this.passResetToken,
this.image,
this.provider,
this.providerId,
this.point,
this.status,
this.createdAt,
this.updatedAt});
Customer.fromJson(Map<String, dynamic> json) {
id = json['id'];
fullName = json['fullName'];
phoneNumber = json['phoneNumber'];
address = json['address'];
email = json['email'];
verifyToken = json['verifyToken'];
passResetToken = json['passResetToken'];
image = json['image'];
provider = json['provider'];
providerId = json['provider_id'];
point = json['point'];
status = json['status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['fullName'] = this.fullName;
data['phoneNumber'] = this.phoneNumber;
data['address'] = this.address;
data['email'] = this.email;
data['verifyToken'] = this.verifyToken;
data['passResetToken'] = this.passResetToken;
data['image'] = this.image;
data['provider'] = this.provider;
data['provider_id'] = this.providerId;
data['point'] = this.point;
data['status'] = this.status;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
class Orderdetails {
String? orderDetails;
String? orderId;
String? productId;
String? productName;
String? productSize;
String? productColor;
String? productPrice;
String? proPurchaseprice;
String? productQuantity;
String? createdAt;
String? updatedAt;
Image? image;
Orderdetails(
{this.orderDetails,
this.orderId,
this.productId,
this.productName,
this.productSize,
this.productColor,
this.productPrice,
this.proPurchaseprice,
this.productQuantity,
this.createdAt,
this.updatedAt,
this.image});
Orderdetails.fromJson(Map<String, dynamic> json) {
orderDetails = json['orderDetails'];
orderId = json['orderId'];
productId = json['ProductId'];
productName = json['productName'];
productSize = json['productSize'];
productColor = json['productColor'];
productPrice = json['productPrice'];
proPurchaseprice = json['proPurchaseprice'];
productQuantity = json['productQuantity'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
image = json['image'] != null ? new Image.fromJson(json['image']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['orderDetails'] = this.orderDetails;
data['orderId'] = this.orderId;
data['ProductId'] = this.productId;
data['productName'] = this.productName;
data['productSize'] = this.productSize;
data['productColor'] = this.productColor;
data['productPrice'] = this.productPrice;
data['proPurchaseprice'] = this.proPurchaseprice;
data['productQuantity'] = this.productQuantity;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.image != null) {
data['image'] = this.image!.toJson();
}
return data;
}
}
class Image {
int? id;
String? productId;
String? image;
String? createdAt;
String? updatedAt;
Image({this.id, this.productId, this.image, this.createdAt, this.updatedAt});
Image.fromJson(Map<String, dynamic> json) {
id = json['id'];
productId = json['product_id'];
image = json['image'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['product_id'] = this.productId;
data['image'] = this.image;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
class Payment {
String? paymentIdPrimary;
String? orderId;
String? paymentType;
Null? senderId;
Null? transectionId;
String? paymentStatus;
Null? bkashFee;
String? createdAt;
String? updatedAt;
Payment(
{this.paymentIdPrimary,
this.orderId,
this.paymentType,
this.senderId,
this.transectionId,
this.paymentStatus,
this.bkashFee,
this.createdAt,
this.updatedAt});
Payment.fromJson(Map<String, dynamic> json) {
paymentIdPrimary = json['paymentIdPrimary'];
orderId = json['orderId'];
paymentType = json['paymentType'];
senderId = json['senderId'];
transectionId = json['transectionId'];
paymentStatus = json['paymentStatus'];
bkashFee = json['bkashFee'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['paymentIdPrimary'] = this.paymentIdPrimary;
data['orderId'] = this.orderId;
data['paymentType'] = this.paymentType;
data['senderId'] = this.senderId;
data['transectionId'] = this.transectionId;
data['paymentStatus'] = this.paymentStatus;
data['bkashFee'] = this.bkashFee;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
class Shipping {
String? shippingPrimariId;
String? customerId;
String? name;
String? phone;
String? address;
String? district;
String? area;
String? shippingfee;
String? note;
String? createdAt;
String? updatedAt;
Shipping(
{this.shippingPrimariId,
this.customerId,
this.name,
this.phone,
this.address,
this.district,
this.area,
this.shippingfee,
this.note,
this.createdAt,
this.updatedAt});
Shipping.fromJson(Map<String, dynamic> json) {
shippingPrimariId = json['shippingPrimariId'];
customerId = json['customerId'];
name = json['name'];
phone = json['phone'];
address = json['address'];
district = json['district'];
area = json['area'];
shippingfee = json['shippingfee'];
note = json['note'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['shippingPrimariId'] = this.shippingPrimariId;
data['customerId'] = this.customerId;
data['name'] = this.name;
data['phone'] = this.phone;
data['address'] = this.address;
data['district'] = this.district;
data['area'] = this.area;
data['shippingfee'] = this.shippingfee;
data['note'] = this.note;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
You don't need to cast it
final List<ProductOrderModel> orderDetailsData = res.data
.map<ProductOrderModel>(ProductOrderModel.fromJson)
.toList();
Try this I am using this ===>
Api Service Class :
class ApiService {
Future<OrderInfo> fetchApi(id) async {
var url = baseUrl + 'customer/order/invoice/$id';
final sharedPreferences = await SharedPreferences.getInstance();
var token = sharedPreferences.getString('accessToken');
var response = await http.get(Uri.parse(url), headers: {
'Authorization': 'Bearer $token',
});
if (response.statusCode == 200) {
var dataResponse = jsonDecode(response.body)['orderInfo'];
OrderInfo user = OrderInfo.fromJson(dataResponse);
return user;
} else {
throw Exception('Failed Get API');
}
}
}
User this function:
Future<OrderInfo> fetchApi(id) async {
var _orderlist = await ApiService().fetchApi(id);
print(productOrderDetailsList);
return productOrderDetailsList.value = _orderlist;
// try {
// } catch (e) {
// print(e);
// }
}

List<dynamic>' is not a subtype of type 'Map<String, dynamic> [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am not so long in flutter 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
Future<TransferResponse> getTransfers(String apiToken) async {
try {
Response response = await _dio.get(
apiEndpoint + "packages",
options: Options(headers: {"Authorization": apiToken}),
);
return TransferResponse.fromJson(response.data);//'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
} catch (error, stacktrace) {
return null;
}
}
class TransferResponse {
List<SenderUser> senderUser;
List<RecipientUser> recipientUser;
TransferResponse({this.senderUser, this.recipientUser});
TransferResponse.fromJson(Map<String, dynamic> json) {
if (json['sender_user'] != null) {
senderUser = new List<SenderUser>();
json['sender_user'].forEach((v) {
senderUser.add(new SenderUser.fromJson(v));
});
}
if (json['recipient_user'] != null) {
recipientUser = new List<RecipientUser>();
json['recipient_user'].forEach((v) {
recipientUser.add(new RecipientUser.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.senderUser != null) {
data['sender_user'] = this.senderUser.map((v) => v.toJson()).toList();
}
if (this.recipientUser != null) {
data['recipient_user'] =
this.recipientUser.map((v) => v.toJson()).toList();
}
return data;
}
}
class SenderUser {
int id;
int recipientUser;
int senderUser;
int coin;
String bill;
int status;
String createdAt;
String updatedAt;
SenderUser(
{this.id,
this.recipientUser,
this.senderUser,
this.coin,
this.bill,
this.status,
this.createdAt,
this.updatedAt});
SenderUser.fromJson(Map<String, dynamic> json) {
id = json['id'];
recipientUser = json['recipient_user'];
senderUser = json['sender_user'];
coin = json['coin'];
bill = json['bill'];
status = json['status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['recipient_user'] = this.recipientUser;
data['sender_user'] = this.senderUser;
data['coin'] = this.coin;
data['bill'] = this.bill;
data['status'] = this.status;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
class RecipientUser {
int id;
int recipientUser;
int senderUser;
int coin;
String bill;
int status;
String createdAt;
String updatedAt;
RecipientUser(
{this.id,
this.recipientUser,
this.senderUser,
this.coin,
this.bill,
this.status,
this.createdAt,
this.updatedAt});
RecipientUser.fromJson(Map<String, dynamic> json) {
id = json['id'];
recipientUser = json['recipient_user'];
senderUser = json['sender_user'];
coin = json['coin'];
bill = json['bill'];
status = json['status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['recipient_user'] = this.recipientUser;
data['sender_user'] = this.senderUser;
data['coin'] = this.coin;
data['bill'] = this.bill;
data['status'] = this.status;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
my response in json
{
"sender_user": [
{
"id": 43,
"recipient_user": 149,
"sender_user": 201,
"coin": 1,
"bill": "3P8FkW4pi2GTR1EXCq7CfAfCkVaSCfPytwR",
"status": 8,
"created_at": "2021-03-20 16:30:02",
"updated_at": "2021-03-20 16:30:02"
}
],
"recipient_user": [
{
"id": 44,
"recipient_user": 201,
"sender_user": 26,
"coin": 2,
"bill": "3P84TFr91wrtveMXimfCY1BeNAVzhAvmf3o",
"status": 8,
"created_at": "2021-03-20 16:32:48",
"updated_at": "2021-03-20 16:32:48"
}
]
}
This is clearly a decoding problem, you are waiting for a list but an object arrives, I advise you to support yourself in this application for the modeling of the classes. (https://app.quicktype.io/)
class TransferResponse {
TransferResponse({
this.senderUser,
this.recipientUser,
});
final List<User> senderUser;
final List<User> recipientUser;
factory TransferResponse.fromJson(Map<String, dynamic> json) => TransferResponse(
senderUser: List<User>.from(json["sender_user"].map((x) => User.fromJson(x))),
recipientUser: List<User>.from(json["recipient_user"].map((x) => User.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"sender_user": List<dynamic>.from(senderUser.map((x) => x.toJson())),
"recipient_user": List<dynamic>.from(recipientUser.map((x) => x.toJson())),
};
}
class User {
User({
this.id,
this.recipientUser,
this.senderUser,
this.coin,
this.bill,
this.status,
this.createdAt,
this.updatedAt,
});
final int id;
final int recipientUser;
final int senderUser;
final int coin;
final String bill;
final int status;
final DateTime createdAt;
final DateTime updatedAt;
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"],
recipientUser: json["recipient_user"],
senderUser: json["sender_user"],
coin: json["coin"],
bill: json["bill"],
status: json["status"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"recipient_user": recipientUser,
"sender_user": senderUser,
"coin": coin,
"bill": bill,
"status": status,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}

List<dynamic> is not a subtype of type in flutter

i am not so long in flutter.I have get method. i have error 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
Future<List<FineResponse>> getAll(String apiToken) async {
try {
Response response = await _dio.get(apiEndpoint + "fines",
options: Options(
headers: {
"Authorization": apiToken
}),
);
return response.data
.map<UserResponse>((el) => UserResponse.fromJson(el)).toList();
} catch (error, stacktrace) {
return null;
}
}
expected response,i did in postman
[
[
{
"id": 1709,
"uin": "188101772006228217193",
"user_id": 1215,
},
{
"id": 1710,
"uin": "188101772006228217194",
"user_id": 1215,
},
{
"id": 1711,
"uin": "1234567890123456789052",
"user_id": 1215,
},
{
"id": 1712,
"uin": "1234567890123456789053",
"user_id": 1215,
}
]
]
class FineResponse {
int id;
String uin;
int userId;
String comment;
String addCoin;
int statusId;
int type;
String createdAt;
String updatedAt;
FineResponse(
{this.id,
this.uin,
this.userId,
this.comment,
this.addCoin,
this.statusId,
this.type,
this.createdAt,
this.updatedAt});
FineResponse.fromJson(Map<String, dynamic> json) {
id = json['id'];
uin = json['uin'];
userId = json['user_id'];
comment = json['comment'];
addCoin = json['add_coin'];
statusId = json['status_id'];
type = json['type'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['uin'] = this.uin;
data['user_id'] = this.userId;
data['comment'] = this.comment;
data['add_coin'] = this.addCoin;
data['status_id'] = this.statusId;
data['type'] = this.type;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
what should i change in my get method?
Since your response.data returns a List<List<Map<String,dynamic>> you need to create a List<List<FineResponse>> if you want the same output like in Postman.
final List<List<FineResponse>> fineResponses =
response.data.map((firstList) =>
firstList.map((data) =>
FineResponse.fromJson(data)
).toList()
).toList()
I think this is not a valid JSON response.
Please check your response here
Check JSON response