Flutter model doesnt work with different responses - flutter

I have a Fluter Model User
class User {
String id;
String name;
String email;
String image;
User({
this.id = "",
this.name = "",
this.email = "",
this.image = "",
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
image: json['image'],
);
}
Map toMap() {
var map = Map<String, dynamic>();
map['id'] = id;
map['name'] = name;
map['email'] = email;
map['image'] = image;
return map;
}
}
And I have a flutter LoginResult that calls user model when I do login
import 'User.dart';
class LoginResult {
String message;
String? token;
User? user;
LoginResult({
this.message = "",
this.token,
this.user,
});
factory LoginResult.fromJson(Map<String, dynamic> json) {
if (json['user'] != null) {
return LoginResult(
message: json['message'],
user: User.fromJson(json['user']),
token: json['token'],
);
} else {
return LoginResult(
message: json['message'],
token: json['token'],
);
}
}
Map toMap() {
var map = Map<String, dynamic>();
map['message'] = message;
map['user'] = user;
map['token'] = token;
return map;
}
}
When I do login, the parsing response body in LoginResults works fine with this result json
{
"message": "logged in success",
"user": {
"rol": 100,
"image": "83f124c1-5a46-469c-8de7-11a90c506a44.jpg",
"_id": "6105c3c8bf76720bfa2e31e9",
"name": "Guillermo Canales Justo",
"email": "test#email.com",
"password": "$2b$10$Z5.RMoRHeyKt7cdFrtubbOzEGjGvHhU19UQEV.mA/ZSunIXqKhYz.",
"__v": 48,
"created": "2021-09-18T06:52:40.995Z",
"id": "6105c3c8bf76720bfa2e31e9"
},
"token": "eyJhbGciOiJIUzI..."
}
But when I update profile user and returns this json, User.fromJson(json_decode(response.body)) returns properties null.
email:null
id:null
image:null
name:null
hashCode:258164629
runtimeType:Type (User)
with this json response
{
"user": {
"rol": 100,
"image": "595ccd2c-1c37-42a7-904f-fdc73b5f89b0.jpg",
"_id": "6105c3c8bf76720bfa2e31e9",
"name": "Guillermo Canales",
"email": "test#email.com",
"password": "$2b$10$Z5.RMoRHey...",
"__v": 48,
"created": "2021-09-18T06:52:40.995Z",
"id": "6105c3c8bf76720bfa2e31e9"
}
}
I cant understand what's wrong with the second parsing.

you will have to get the Users from the json.
change this line
User.fromJson(json_decode(response.body))
to
User.fromJson(json_decode(response.body)['user'])

Related

How to make complex Model for my Flutter Dart Project?

I need to create a dart Model class for this complex json .Please any one help
{
"status": "1",
"list": {
"4": [
{
"id": "1289",
"t": "Mutton biriyani",
"p": "21",
"i": "1289_5305.jpg",
"v": "0"
},
{
"id": "1288",
"t": "Chicken biriyani",
"p": "14",
"i": "1288_5339.jpg",
"v": "0"
}
]
}
}
can any one help
you can create modal of every json using this website json-to-dart.
and after making some changes the modal for your jsong would be something like this
class Modal {
String? status;
List<FoodList>? foodList;
Modal({this.status, this.foodList});
Modal.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['list']["4"] != null) {
foodList = <FoodList>[];
json['list']["4"].forEach((v) {
foodList!.add(new FoodList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.foodList != null) {
data['list']["4"] = this.foodList!.map((v) => v.toJson()).toList();
}
return data;
}
}
class FoodList {
String? id;
String? t;
String? p;
String? i;
String? v;
FoodList({this.id, this.t, this.p, this.i, this.v});
FoodList.fromJson(Map<String, dynamic> json) {
id = json['id'];
t = json['t'];
p = json['p'];
i = json['i'];
v = json['v'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['t'] = this.t;
data['p'] = this.p;
data['i'] = this.i;
data['v'] = this.v;
return data;
}
}
Here is an example of a Dart Model class that could be used to parse the JSON you provided
class Model {
final String status;
final List list;
Model({this.status, this.list});
factory Model.fromJson(Map<String, dynamic> json) {
return Model(
status: json['status'],
list: json['list'],
);
}
}
And you can use it like this
final jsonString = '{ "status": "1", "list": { "4": [ { "id": "1289", "t": "Mutton biriyani", "p": "21", "i": "1289_5305.jpg", "v": "0" }, { "id": "1288", "t": "Chicken biriyani", "p": "14", "i": "1288_5339.jpg", "v": "0" } ] } }';
final jsonMap = jsonDecode(jsonString);
final data = Model.fromJson(jsonMap);
Note that the List class is a basic type in dart, so it is not suitable for your json structure. In this case, you need to define a custom class for the "list" field.
class FoodList {
String status;
Map<String, List<Food>> list;
FoodList({this.status, this.list});
factory FoodList.fromJson(Map<String, dynamic> json) {
var list = json['list'] as Map;
var foodList = list.map((key, value) {
return MapEntry(key, (value as List).map((e) => Food.fromJson(e)).toList());
});
return FoodList(status: json['status'], list: foodList);
}
}
class Food {
String id;
String title;
String price;
String image;
String v;
Food({this.id, this.title, this.price, this.image, this.v});
factory Food.fromJson(Map<String, dynamic> json) {
return Food(
id: json['id'],
title: json['t'],
price: json['p'],
image: json['i'],
v: json['v']);
}
}

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();
}))

Flutter - Dart parsing json data array returns type 'List<dynamic>' is not a subtype of type 'List<BusinessTest>'

I'm trying to parse a json file using a custom model, I always get the error type 'List<dynamic>' is not a subtype of type 'List<BusinessTest>' and I don't know how I can fix my code. Also is it a good idea to always use nullable type in variables when you parse json files?
This is a Json example of my data:
{
"businesses": [{
"id": "1",
"alias": "123",
"name": "aaa",
"image_url": "xxx.jpg",
"is_closed": false,
"url": ".com",
"review_count": 26,
"rating": 5.0
},
{
"id": "2",
"alias": "123",
"name": "aaa",
"image_url": "xxx.jpg",
"is_closed": false,
"url": ".com",
"review_count": 26,
"rating": 5.0
}
]
}
Here is the model code I've made in order to parse the Json:
class BusinessSearch {
final List<BusinessTest> businesses;
final int total;
BusinessSearch(this.businesses, this.total);
BusinessSearch.fromJson(Map<String, dynamic> json)
: businesses = json['businesses'],
total = json['total'];
}
class BusinessTest {
final String? name;
final String? imageUrl;
final bool? isClosed;
final String? url;
final int? reviewCount;
BusinessTest(
this.name, this.imageUrl, this.isClosed, this.url, this.reviewCount);
BusinessTest.fromJson(Map<String, dynamic> json)
: name = json['name'],
imageUrl = json['image_url'],
isClosed = json['is_closed'],
url = json['url'],
reviewCount = json['review_count'];
}
This is how I'm trying to parse it:
void getData() async {
try {
String url = 'url';
NetworkHelp network = NetworkHelp(url: url);
var data = await network.getData();
Map<String, dynamic> businessMap = await jsonDecode(data);
var business = BusinessSearch.fromJson(businessMap);
} catch (e) {
print(e);
}
}
You have to update your BusinessSearch model like this.
class BusinessSearch {
BusinessSearch({
this.businesses,
this.total,
});
List<Business> businesses = [];
int total;
factory BusinessSearch.fromJson(Map<String, dynamic> json) => BusinessSearch(
businesses: List<Business>.from(json["businesses"].map((x) => Business.fromJson(x))),
total: json['total']
);
Map<String, dynamic> toJson() => {
"businesses": List<dynamic>.from(businesses.map((x) => x.toJson())),
"total": total,
};
}
class Business {
Business({
this.id,
this.alias,
this.name,
this.imageUrl,
this.isClosed,
this.url,
this.reviewCount,
this.rating,
});
String id;
String alias;
String name;
String imageUrl;
bool isClosed;
String url;
int reviewCount;
int rating;
factory Business.fromJson(Map<String, dynamic> json) => Business(
id: json["id"],
alias: json["alias"],
name: json["name"],
imageUrl: json["image_url"],
isClosed: json["is_closed"],
url: json["url"],
reviewCount: json["review_count"],
rating: json["rating"],
);
Map<String, dynamic> toJson() => {
"id": id,
"alias": alias,
"name": name,
"image_url": imageUrl,
"is_closed": isClosed,
"url": url,
"review_count": reviewCount,
"rating": rating,
};
}

How to Parse Nested JSON ln Flutter?

{
"data": {
"Address": "ff9",
"CityID": "1",
"CityName": "Ahmedabad",
"CompanyName": "bs Soffy",
"CreditDays": "12",
"CusotmerID": "45",
"Email": "f#gmail.com",
"GSTNo": "1234",
"IsApproved": "False",
"Lat": "",
"Long": "",
"Mobile": "1234567890",
"Pincode": "",
"Route": "",
"StateID": "1",
"StateName": "Gujrat",
"UniqueNumber": ""
},
"message": "Data updated successfully",
"status": 200
}
List<GetCustomer> Customerlist = [];
Future<List<GetCustomer>> getPostApi() async {
final response = await http.post(
Uri.parse(
'XYZ'),
headers: {
"Content-Type": "application/json",
"Charset": "utf-8",
},
body: (jsonEncode({'UserID': 1})));
if (response.statusCode == 200) {
// Map<String, dynamic> map = json.decode(response.body);
Map<String, dynamic> map =
new Map<String, dynamic>.from(json.decode(response.body));
List<dynamic> data = map["data"];
Customerlist.clear();
for (var i in data) {
Customerlist.add(GetCustomer.fromJson(i));
}
return Customerlist;
} else {
return Customerlist;
}
} -> Eror When Calling
You can use app.quicktype.io or any other online sites for parsing your model so fast. Otherwise you need to write manually.
// To parse this JSON data, do
//
// final data = dataFromJson(jsonString);
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
Data({
this.data,
this.message,
this.status,
});
DataClass data;
String message;
int status;
factory Data.fromJson(Map<String, dynamic> json) => Data(
data: DataClass.fromJson(json["data"]),
message: json["message"],
status: json["status"],
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
"message": message,
"status": status,
};
}
class DataClass {
DataClass({
this.address,
this.cityId,
this.cityName,
this.companyName,
this.creditDays,
this.cusotmerId,
this.email,
this.gstNo,
this.isApproved,
this.lat,
this.long,
this.mobile,
this.pincode,
this.route,
this.stateId,
this.stateName,
this.uniqueNumber,
});
String address;
String cityId;
String cityName;
String companyName;
String creditDays;
String cusotmerId;
String email;
String gstNo;
String isApproved;
String lat;
String long;
String mobile;
String pincode;
String route;
String stateId;
String stateName;
String uniqueNumber;
factory DataClass.fromJson(Map<String, dynamic> json) => DataClass(
address: json["Address"],
cityId: json["CityID"],
cityName: json["CityName"],
companyName: json["CompanyName"],
creditDays: json["CreditDays"],
cusotmerId: json["CusotmerID"],
email: json["Email"],
gstNo: json["GSTNo"],
isApproved: json["IsApproved"],
lat: json["Lat"],
long: json["Long"],
mobile: json["Mobile"],
pincode: json["Pincode"],
route: json["Route"],
stateId: json["StateID"],
stateName: json["StateName"],
uniqueNumber: json["UniqueNumber"],
);
Map<String, dynamic> toJson() => {
"Address": address,
"CityID": cityId,
"CityName": cityName,
"CompanyName": companyName,
"CreditDays": creditDays,
"CusotmerID": cusotmerId,
"Email": email,
"GSTNo": gstNo,
"IsApproved": isApproved,
"Lat": lat,
"Long": long,
"Mobile": mobile,
"Pincode": pincode,
"Route": route,
"StateID": stateId,
"StateName": stateName,
"UniqueNumber": uniqueNumber,
};
}

Flutter : Get data on Nested json

hi stackers i have a problem with returning nested data in array object using flutter, the data has shown but i cant get what i want to get i have a response like this from my backend
"meta": {
"code": 200,
"status": "success",
"message": "Data list transaksi berhasil diambil"
},
"data": {
"current_page": 1,
"data": [
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1,
}
}
]
}
],
}
}
response above is from my backend that success fully return in my response print() in flutter but i want to get the nested data in items.menus its return error Class'_InternalLinkedHashMap<String, dynamic>'has no instance getter 'menus'
for better understanding my question ill provide full model, provider and my services
this is my service getOrderList() function that i call in the futureBuilder
var url = '$baseUrl/transaction';
var headers = {
'Content-type': 'application/json',
'Authorization': 'Bearer ${userModel.token}'
};
var response = await http.get(Uri.parse(url), headers: headers);
// print(response.body);
// print('berhasil get kategori');
if (response.statusCode == 200) {
List data = json.decode(response.body)['data']['data'];
List<TransactionModel> transaction = [];
for (var item in data) {
transaction.add(TransactionModel.fromJson(item));
}
// print(transaction);
return transaction;
} else {
throw Exception('Gagal get Categori');
}
}
and this is my model code
class TransactionModel {
int id;
int users_id;
String invoice;
int seat_number;
double total_price;
String payment_method;
String status;
List items;
// List menu;
TransactionModel({
this.id,
this.users_id,
this.invoice,
this.seat_number,
this.total_price,
this.payment_method,
this.status,
this.items,
// this.menu,
});
TransactionModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
users_id = json['users_id'];
invoice = json['invoice'];
seat_number = json['seat_number'];
total_price = double.parse(json['total_price'].toString());
payment_method = json['payment_method'];
status = json['status'];
items = json['items'];
// menu = json['items']['menus'];
}
Map<String, dynamic> toJson() {
return {
'id': id,
'users_id': users_id,
'invoice': invoice,
'seat_number': seat_number,
'items': items,
'total_price': total_price,
'payment_method': payment_method,
'status': status,
// 'menu': menu,
};
}
}
i already change the model data and try much method but its still not working, thats all on my code what should i do to call items.menus in result ?
It seems to be a problem within the model, you can use a json to dart to make model class from raw json. Keep the fetching logic as it is.
Json
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1
}
}
]
}
Model class
// To parse this JSON data, do
//
// final transactionModel = transactionModelFromMap(jsonString);
import 'dart:convert';
class TransactionModel {
TransactionModel({
this.id,
this.usersId,
this.invoice,
this.seatNumber,
this.totalPrice,
this.paymentMethod,
this.status,
this.items,
});
final int id;
final int usersId;
final String invoice;
final int seatNumber;
final int totalPrice;
final String paymentMethod;
final String status;
final List<Item> items;
factory TransactionModel.fromJson(String str) => TransactionModel.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory TransactionModel.fromMap(Map<String, dynamic> json) => TransactionModel(
id: json["id"],
usersId: json["users_id"],
invoice: json["invoice"],
seatNumber: json["seat_number"],
totalPrice: json["total_price"],
paymentMethod: json["payment_method"],
status: json["status"],
items: List<Item>.from(json["items"].map((x) => Item.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"id": id,
"users_id": usersId,
"invoice": invoice,
"seat_number": seatNumber,
"total_price": totalPrice,
"payment_method": paymentMethod,
"status": status,
"items": List<dynamic>.from(items.map((x) => x.toMap())),
};
}
class Item {
Item({
this.id,
this.menusId,
this.transactionsId,
this.quantity,
this.menus,
});
final int id;
final int menusId;
final int transactionsId;
final int quantity;
final Menus menus;
factory Item.fromJson(String str) => Item.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Item.fromMap(Map<String, dynamic> json) => Item(
id: json["id"],
menusId: json["menus_id"],
transactionsId: json["transactions_id"],
quantity: json["quantity"],
menus: Menus.fromMap(json["menus"]),
);
Map<String, dynamic> toMap() => {
"id": id,
"menus_id": menusId,
"transactions_id": transactionsId,
"quantity": quantity,
"menus": menus.toMap(),
};
}
class Menus {
Menus({
this.id,
this.name,
this.price,
this.description,
this.categoriesId,
});
final int id;
final String name;
final int price;
final String description;
final int categoriesId;
factory Menus.fromJson(String str) => Menus.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Menus.fromMap(Map<String, dynamic> json) => Menus(
id: json["id"],
name: json["name"],
price: json["price"],
description: json["description"],
categoriesId: json["categories_id"],
);
Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"price": price,
"description": description,
"categories_id": categoriesId,
};
}