JsonUnsupportedObjectError was thrown while handling a gesture - Flutter - json

I'm working on a datable that displays some users with their information and in which each row can change its 'role' and be removed from the site it's associated with by sending a JSON message to kafka into the DB. For this purpose, I added a dropdown button to change their roles and a 'remove' button to remove the user from the site.
But whenever I trigger the 'remove button' or change the role dropdown validation, I receive the following error:
EXCEPTION CAUGHT BY GESTURE
The following JsonUnsupportedObjectError was thrown while handling a gesture:
Converting object to an encodable object failed: Instance of 'User'
When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49
throw_
dart-sdk/lib/convert/json.dart 794:7
writeObject
dart-sdk/lib/convert/json.dart 875:7
writeMap
dart-sdk/lib/convert/json.dart 830:21
writeJsonValue
dart-sdk/lib/convert/json.dart 785:9
writeObject
dart-sdk/lib/convert/json.dart 983:16
printOn
dart-sdk/lib/convert/json.dart 968:5
stringify
dart-sdk/lib/convert/json.dart 345:30
convert
dart-sdk/lib/convert/json.dart 231:45
encode
dart-sdk/lib/convert/json.dart 114:10
jsonEncode
packages/frontend/data/socketDataStreamController.dart 343:33
editUserSite
packages/frontend/screens/pagesNavigator/sitesManagementPage/sitesUsers.dart
237:64 <fn>
My user class is the following:
class User {
final String userId;
String firstName;
String lastName;
String email;
final String company;
String phoneNumber;
final String userRole;
final Uint8List imageBuffer;
final bool admin;
String? authToken;
String country;
String language;
List<dynamic> notifications;
String siteRole;
User(
{required this.userId,
required this.firstName,
required this.lastName,
required this.email,
required this.company,
required this.phoneNumber,
required this.imageBuffer,
required this.userRole,
required this.admin,
required this.country,
required this.language,
required this.notifications,
required this.siteRole
});
/// Generate new user object from json
User.fromJSON(
Map<String, dynamic> json,
) : userId = json["_id"] ?? "",
firstName = json["firstName"] ?? "",
lastName = json["lastName"] ?? "",
email = json["email"] ?? "",
company = json["company"] ?? "",
phoneNumber = json["phoneNumber"] ?? "",
userRole = json["userRole"] ?? "",
imageBuffer = Uint8List(0),
authToken = json["token"],
admin = json["admin"] ?? false,
country = json["country"] ?? "",
language = json["language"] ?? "",
notifications = json["notifications"] ?? [],
siteRole = json["siteRole"] ?? "";
#override
String toString() {
return "User: ${jsonEncode({
"userId": userId,
"name": "$firstName $lastName",
"email": email,
"company": company,
"phoneNumber": phoneNumber,
"userRole": userRole,
"admin": admin,
"country": country,
"language": language,
"siteRole": siteRole
})}";
}
}
This is the Button inside the alert dialog that triggers the JSON
ElevatedButton(
child: Text('Yes, remove.'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.grey),
onPressed: () {
final userRoleChange = {
"siteId": widget.site.id,
"userId": user,
"status": 0
};
globals.socketController.editUserSite(userRoleChange);
Navigator.of(context).pop()
},
),
This is the main.js backend function that connects with kafka:
socket.on("editUserSite", async (message) => {
// console.log('on editUserSite')
let result = true;
const userData = JSON.parse(message);
// console.log(userData)
var requestId = Date.now().toString() + "_backend"
let dbRequest = topicsLib["userDB-read"]
dbRequest.query_id = requestId,
dbRequest.collection = "sites",
dbRequest.object_id = [userData.siteId]
dbRequest.requester = "backend"
dbRequest.field = [
"users"
]
adminProducer.send( {
topic: "userDB-read",
messages: [{ value: JSON.stringify(dbRequest) }],
});
const dbUserResponse = await kafkaDbResponse(requestId, logger);
if (typeof(dbUserResponse.data) == String) {
logger.error("Error when fetching data" + dbUserResponse)
throw new Error("Error when fetching data")
}
// console.log(dbUserResponse)
usersList = []
for (d of dbUserResponse.data[0].users) {
usersList.push(d)
}
// console.log(usersList)
objIndex = usersList.findIndex((obj => obj.userId == userData.userId));
console.log(objIndex)
//The users dont exist , we need to add a user
if (objIndex == -1) {
usersList.push({
userId:userData.userId,
role:userData.role,
})
} else {
//Update or Remove user
if (userData.status == 0) {
usersList.splice(objIndex, 1);
} else {
usersList[objIndex].role = userData.role
}
}
console.log(usersList)
let dbUpdatePayload = topicsLib["userDB-write"]
const dbUpdateMessageId = hashCode(Date.now().toString());
dbUpdatePayload.query_id = dbUpdateMessageId,
dbUpdatePayload.collection = "sites",
dbUpdatePayload.object_id = userData.siteId
dbUpdatePayload.requester = "backend"
dbUpdatePayload.append = false
dbUpdatePayload.field = ["users"]
dbUpdatePayload.data = [usersList]
dbUpdatePayload.convert_to_object_id = true
dbUpdatePayload.field_to_object_id = "userId"
console.log(dbUpdatePayload)
await adminProducer.send( {
topic: "userDB-write",
messages: [
{
value: JSON.stringify(dbUpdatePayload),
},
],
});
//#ts-ignore
await sleep(80);
if (result) {
response = {
'status' : 200,
'message' : 'Site updated',
}
} else {
response = {
'status' : 400,
'message' : 'error',
}
}
socket.emit("editUserSiteResponse", response)
})
And this is the socketdataStreamcontroller that consumes it on the frontend:
void editUserSite(userRoleChange) {
if (!socket.connected) {
return;
}
socket.emit("editUserSite", jsonEncode(userRoleChange));
}
How can I solve this issue?

Related

How to get json response in flutter using POST method?

I am beginner in flutter. Please help me get and set below json data into model in flutter. I am using POST method.
'''
{
"success": 1,
"data": {
"user_id": 2,
"email": "ajay.singhal#ollosoft1.com",
"phone": "9414905280",
"password": "1436a615e62482ba4f075c1d4a4fd94b",
"account_status": "Active",
"date_of_birth": "1953-09-07T00:00:00.000Z",
"address": "Jaipur Rajasthan",
"profile_url": "http://18.217.236.99:4200/assets/profile_img/2/RBI-keeps-policy-rate-unchanged-1.jpg",
"first_name": "Ajay",
"last_name": "singhal"
}
}
'''
Below is my Model class named UserInfoModel
import 'UserInfoDataModel.dart';
class UserInfoModel {
final int success;
final UserInfoDataModel data;
UserInfoModel(this.success, this.data);
factory UserInfoModel.fromJson(dynamic json) {
if (json['data'] != null) {
var tagObjsJson = json['data'];
UserInfoDataModel _tags =
tagObjsJson.map((tagJson) => UserInfoDataModel.fromJson(tagJson));
return UserInfoModel(json['success'] as int, _tags);
}
}
#override
String toString() {
return '{${this.success}, ${this.data}}';
}
}
Below is submodel name is UserInfoDataModel
import 'package:flutter/material.dart';
class UserInfoDataModel {
int user_id;
String email;
String phone;
String password;
String account_status;
String date_of_birth;
String address;
String profile_url;
String first_name;
String last_name;
UserInfoDataModel(
{this.user_id,
this.email,
this.phone,
this.password,
this.account_status,
this.date_of_birth,
this.address,
this.profile_url,
this.first_name,
this.last_name});
factory UserInfoDataModel.fromJson(Map<String, dynamic> json) {
return UserInfoDataModel(
user_id: json['user_id'] as int,
email: json['email'],
phone: json['phone'],
password: json['password'],
account_status: json['account_status'],
date_of_birth: json['date_of_birth'],
address: json['address'],
profile_url: json['profile_url'],
first_name: json['first_name'],
last_name: json['last_name'],
);
}
}
My APi Call is below Using POST Method
I am successfully getting response, but unable to set in model
UserInfoModel _userInfoModel;
UserInfoDataModel _userInfoDataModel;
String url = BaseURLHeaders().getBaseURl() + "userInfo";
Map headers = BaseURLHeaders().getHeader();
#override
void initState() {
// TODO: implement initState
super.initState();
getData();
}
Future<UserInfoModel> getData() async {
String user_id = "1";
var mapData = new Map<String, dynamic>();
mapData['user_id'] = user_id;
// mapData['first_name'] = firstName;
var response = await http.post(
url,
headers: headers,
body: mapData,
);
setState(() {
print("userInfoDetails: ${response.body}");
print("urlTop: ${url}");
print("headersTop: ${headers}");
print("responseCode: ${response.statusCode}");
});
if (response.statusCode == 200) {
var res = json.decode(response.body);
_userInfoModel = UserInfoModel.fromJson(res);
if (_userInfoModel.success == 1) {
var data = res["data"];
setState(() {
print("responseBody: ${res}");
print("userInfoSuccess: ${_userInfoModel.success}");
print("dataVaalue: ${data["email"]}");
print("urlBelow: ${url}");
print("headersBelow: ${headers}");
});
}
}
}
UserInfoDataModel _tags =
tagObjsJson.map((tagJson) => UserInfoDataModel.fromJson(tagJson));
here you are actually treated tagObjsJson as a list. but it is a JsonObject so there you don't want the map function.
you can access the object as
UserInfoDataModel _tags =UserInfoDataModel.fromJson(tagJson);
You can use json_serializer in flutter. See flutter docs.
If you use IntelliJ IDEA, you can use DartToJson package. It generates automatically for you and you can use fromJson and toJson method.

Problem with fetch: '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

I'm trying to fetch data from an API, but I keep getting this error.
Problem with fetch: '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List'
Please tell me how to fix this code.
Model.dart
class ComprovanteModel {
ComprovantesInfoModel jsonResponse;
String error;
ComprovanteModel({this.jsonResponse, this.error});
ComprovanteModel.fromJson(Map<String, dynamic> json)
: jsonResponse = ComprovantesInfoModel.fromJson(json['json_response']),
error = '';
ComprovanteModel.withError(String errorValue)
: jsonResponse = null,
error = errorValue;
}
class ComprovanteInfoModel {
String clientFormalName;
int volumes;
int duration;
CheckpointsModel checkpoint;
ComprovanteInfoModel({
this.clientFormalName,
this.duration,
this.volumes,
this.checkpoint,
});
ComprovanteInfoModel.fromJson(Map<String, dynamic> json)
: clientFormalName = json['client_formal_name'],
checkpoint = CheckpointsModel.fromJson(json['checkpoint']),
volumes = json['volumes'],
duration = json['duration'];
}
class CheckpointModel {
int checkpointId;
String arrivalTime;
int status;
CheckpointModel({
this.checkpointId,
this.arrivalTime,
this.status,
});
CheckpointModel.fromJson(Map<String, dynamic> json)
: checkpointId = json['checkpoint_id'],
arrivalTime = json['arrival_time'],
status = json['status'];
}
class CheckpointsModel {
List<CheckpointModel> checkpoint;
CheckpointsModel({this.checkpoint});
CheckpointsModel.fromJson(List<dynamic> jsonList)
: checkpoint = jsonList.map((e) => CheckpointModel.fromJson(e)).toList();
}
The API response:
{
"json_response": [
{
"client_formal_name": "",
"deadline": null,
"volumes": 1,
"duration": 5,
"depot_id": 20,
"service_id": 109856,
"georef_provider": "ap_geocoder",
"checkpoint": {
"checkpoint_id":,
"arrival_time": "",
"duration":,
"status": 1,
"event_id": 5,
"resources": [
{
"content_type": "PHOTO",
"service_event_effect_id": 58,
"content": "em+ndG6XtE2unp",
"content_label": "",
"user_effect_unique_code": ""
},
{
"content_type": "RECEPTOR_INFO",
"service_event_effect_id": 61,
"content": "{\"user_relationship_unique_code\":\"\",\"is_expected_receiver\":\"true\",\"document\":\"65979973000240\",\"name\":\"",\"description\":\"",\"id\":\"1\"}",
"content_label": "",
"user_effect_unique_code": "2"
}
],
"event_description": "",
"operation_date": "",
"obs": "",
"is_assistant": false,
"image": "{\"description\": \"Documento\", \"photo\": \""}"
},
"final_attendance_window_b": null
}
]
}
I want to access the checkpoint item, then the resource item(which I think is the same process as the checkpoint). I am using the list but I don't think is right, I am suppose to use map but I don't know how. Please show me a way.
Change this:
ComprovanteModel.fromJson(Map<String, dynamic> json)
: jsonResponse = ComprovantesInfoModel.fromJson(json['json_response']),
error = '';
To this:
ComprovanteModel.fromJson(Map<String, dynamic> json)
: jsonResponse = ComprovantesInfoModel.fromJson(json['json_response'][0]), //added [0] here.
error = '';
If you look closely at your response, it does have the map that you need, but this map is actually inside a list, notice the square brackets [ ] around the {} in "json_response": [.
The map that you need to access, is at index[0] of this list, then everything will work fine.
Second thing, this:
CheckpointsModel.fromJson(List<dynamic> jsonList)
: checkpoint = jsonList.map((e) => CheckpointModel.fromJson(e)).toList();
}
You are telling Flutter that you will pass an object of type List<dynamic> , but in the json you post, "checkpoint": { is not a list, it's a map. But even so, this map has only one checkpoint.
To answer your last question
I wanna access the checkpoint item, then the resource item(wich i
think is the same process as the checkpoint).
"resources": [ is indeed a list of Maps. In your code you did not post your resources model, but I'm assuming you want a List<Resources> and not List<CheckPoint>, it'll look like this:
class SingleResourceModel {
String contentType;
int serviceId;
String content;
String contentLabel;
String uniqueCode;
SingleResourceModel({
this.contentType,
this.serviceId,
this.content,
this.contentLabel,
this.uniqueCode
});
SingleResourceModel.fromJson(Map<String, dynamic> json)
: contentType = json['content_type'],
serviceId = json['service_event_effect_id'],
content = json['content'];
contentLabel = json['content_label'],
uniqueCode = json['user_effect_unique_code'];
}
class ListResourceModel {
List<SingleResourceModel> resourcesList;
ListResourceModel({this.resourcesList});
ListResourceModel.fromJson(List<Map<String, dynamic>> jsonList)
: resourcesList = jsonList.map((e) => SingleResourceModel.fromJson(e)).toList();
}
Finally, you can modify your CheckPoint model, and add to it a ListResourceModel, to look like this in the end:
class CheckpointModel {
int checkpointId;
String arrivalTime;
int status;
ListResourceModel resourcesList;
CheckpointModel({
this.checkpointId,
this.arrivalTime,
this.status,
this.resourcesList
});
CheckpointModel.fromJson(Map<String, dynamic> json)
: checkpointId = json['checkpoint_id'],
arrivalTime = json['arrival_time'],
status = json['status'],
resourcesList= json['resources'];
}
Now, you should be all set.

How can i return User() in Json from Django after logging in?

In my backend algorithm when i login it returns full user details like this:
For Example:
# If server returns 200 it also returns user info
"token": "token here",
"user": {
"id": "id here",
"email": "userabc#gmail.com",
"username": "userabc",
"first_name": null,
"last_name": null,
"sign_up_date": "2020-07-30T11:56:12.703000Z",
"last_login": "2020-08-03T12:34:24.305638Z"
}
I have a Json function like this:
Future<User> signIn(String email, String password) async {
...# Necessary function
if (response.statusCode == 200) {
return User();
}
else {
...
}
It authenticates fine,but i don't know how to return the user.How can i do it,does anybody have any idea?
Update 1:
Update 2:
1st Error : User = list.map((model) => U.fromJson(model)).toList();
2nd Error : User = list.map((model) => U.fromJson(model)).toList();
3rd Error : User = list.map((model) => U.fromJson(model)).toList();
Rest of the code works fine.
Update 3:
You must create User model from json:
Map<String, dynamic> map = json.decode(response.body);
Iterable list = map['user'];
User = list.map((model) => U.fromJson(model)).toList();
And before:
User(
this.id,
this.email,
this.userName,
this.firstName,
this.lastName,
this.signUpDate,
this.lastLogin,
);
User.fromJson(Map json)
: id = json['id'],
email = json['email'],
userName = json['username'],
firstName = json['first_name'],
lastName = json['last_name'],
signUpDate = json['sign_up_date'],
lastLogin = json['last_login'];

For loop returning only first json Object Flutter

While I tried to fetch data from a JSON am only able to return the first object.
I had mentioned the statement which I think the issue is. I want to return all the available object from the JSON so that I shall display it in a list of cards. I need to return all the JSON objects and pass it to another page containing list of cards. If anyone knows the solution please help me fix it.
Thanks in advance.
import 'dart: convert';
import 'package:flutter/cupertino.dart';
import 'package:tts/tts.dart';
import 'package:wiizboo/service/Chatmsg_service.dart';
import 'package:wiizboo/widget/a%20copy.dart';
import 'package:wiizboo/widget/chat_in_message.dart';
import 'package:wiizboo/widget/chat_out_message.dart';
import 'package:wiizboo/widget/form.dart';
import 'package:wiizboo/widget/image_camera.dart';
import 'package:wiizboo/widget/image_gallery.dart';
class ChatMessageModel with ChangeNotifier {
String data;
List accntdet;
ChatmessageService chatservice = ChatmessageService();
List<Widget> messages = <Widget>[];
ChatMessageModel() {
sendMsg("Hi");
}
Future handlesubmission(String chattext) {
Widget message = new ChatInMessage(
text: chattext,
name: "Me",
type: true,
);
addMsg(message);
sendMsg(chattext);
}
addMsg(Widget msg) {
messages.insert(0, msg);
notifyListeners();
}
sendMsg(String msg) {
chatservice.SendMsg(msg).then((String msg) {
responseBuilder(msg);
});
}
responseBuilder(String msg) {
Widget message;
String identifier = '';
var arr = msg.split("~");
if (arr.length > 1) {
identifier = arr[0];
msg = arr[1];
} else {
msg = arr[0];
}
switch (identifier) {
case 'email_phone':
message = new Forms(onSubmitted: (String val) {
Widget a = new ChatInMessage(
text: val,
name: "Me",
type: true,
);
addMsg(a);
sendMsg(val);
});
break;
case 'selfie':
message = new ImageCamera(onSubmitted: (String imageres) {
Widget b = new ChatInMessage(
text: imageres,
name: "Me",
type: true,
);
sendMsg(imageres);
});
break;
case 'aadhar':
message = new ImageGalery(onSubmitted: (String imageres) {
Widget b = new ChatInMessage(
text: imageres,
name: "Me",
type: true,
);
sendMsg(imageres);
});
break;
case 'account_info':
print(msg);
data = msg;
String receivedJson = data;
List<dynamic> list = json.decode(receivedJson);
accntdet = list;
int l = list.length;
print(l);
//------------ the statement --------//
for (dynamic account in accntdet) {
message = new AccountInfo(
l: l,
iban: account['ibn_no'],
accno: account['account_no'],
sort: account['sort-code'],
currency: account['currency'],
);
}
//----------//
print(message);
break;
default:
message = new ChatOutMessage(
text: msg,
name: "WzBoo..",
);
Tts.speak(msg);
}
addMsg(message);
}
}
Change this bloc
class ChatMessageModel with ChangeNotifier {
String data;
List accntdet;
ChatmessageService chatservice = ChatmessageService();
List<Widget> messages = <Widget>[];
ChatMessageModel() {
sendMsg("Hi");
}
Future handlesubmission(String chattext) {
Widget message = new ChatInMessage(
text: chattext,
name: "Me",
type: true,
);
addMsg(message);
sendMsg(chattext);
}
addMsg(Widget msg) {
messages.insert(0, msg);
notifyListeners();
}
sendMsg(String msg) {
chatservice.SendMsg(msg).then((String msg) {
responseBuilder(msg);
});
}
responseBuilder(String msg) {
Widget message;
String identifier = '';
var arr = msg.split("~");
if (arr.length > 1) {
identifier = arr[0];
msg = arr[1];
} else {
msg = arr[0];
}
switch (identifier) {
case 'email_phone':
message = new Forms(onSubmitted: (String val) {
Widget a = new ChatInMessage(
text: val,
name: "Me",
type: true,
);
addMsg(a);
sendMsg(val);
});
break;
case 'selfie':
message = new ImageCamera(onSubmitted: (String imageres) {
Widget b = new ChatInMessage(
text: imageres,
name: "Me",
type: true,
);
sendMsg(imageres);
});
addMsg(message);
break;
case 'aadhar':
message = new ImageGalery(onSubmitted: (String imageres) {
Widget b = new ChatInMessage(
text: imageres,
name: "Me",
type: true,
);
sendMsg(imageres);
});
break;
case 'account_info':
print(msg);
data = msg;
String receivedJson = data;
List<dynamic> list = json.decode(receivedJson);
accntdet = list;
int l = list.length;
print(l);
//------------ the statement --------//
for (dynamic account in accntdet) {
message = new AccountInfo(
l: l,
iban: account['ibn_no'],
accno: account['account_no'],
sort: account['sort-code'],
currency: account['currency'],
);
print(message);
addMsg(message);
}
//----------//
break;
default:
message = new ChatOutMessage(
text: msg,
name: "WzBoo..",
);
Tts.speak(msg);
addMsg(message);
}
}
}

flutter : nested json parsing list

I am trying to call Name and Fees from my json code
it is nested array from main array of my json the main array i can deal with it but the sub array i can't
"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
],
And I can't do that because of the error here when iam tring to call 'Name' and 'Fees'
type 'List<ExtraServices>' is not a subtype of type 'String'
and this is my class for mapping tour guide data to use it in list view
class TourGuide{
String id;
String name;
String email;
String password;
List<ExtraServices> extraService;
TourGuide({
this.id,
this.name,
this.email,
this.password,
this.extraService,
});
TourGuide.fromJson(Map<String, dynamic> json){
List<dynamic> extra = json['guideExtraServices'];
List<ExtraServices> extraList = extra.map((i) => ExtraServices.fromJson(i)).toList();
id = json['id'].toString();
name = json['displayName'];
email = json['email'];
password = json['password'];
extraService=extraList;
}
}
and this is a Extra Services class which tour guide class depend on to get the sub array
class ExtraServices{
String name;
double fees;
ExtraServices({
this.name,
this.fees
});
ExtraServices.fromJson(Map<String, dynamic> json){
name = json['Name'];
fees = json['Fees'].toDouble();
}
}
my provider method for decode json using for api
Future<dynamic> tourGuideList() async {
_isLoading = true;
notifyListeners();
print('Starting request');
http.Response response = await http.get(Environment.tourGuide,
headers: Environment.requestHeader);
print('Completed request');
print('respond data : ${response.body}');
Map<String, dynamic> res = json.decode(response.body);
var results;
if (res['code'] == 200) {
print('start load tourguide');
_tourGuide = [];
res['message'].forEach((v) {
_tourGuide.add(new TourGuide.fromJson(v));
});
results = true;
} else {
results =
FailedRequest(code: 400, message: res['error'], status: false);
}
_isLoading = false;
notifyListeners();
return results;
}
and I don't know why I have an error and I can't fix it
I think your json should be like this in total:
{"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
]}
Try
// To parse this JSON data, do
//
// final tourGuide = tourGuideFromJson(jsonString);
import 'dart:convert';
TourGuide tourGuideFromJson(String str) => TourGuide.fromJson(json.decode(str));
String tourGuideToJson(TourGuide data) => json.encode(data.toJson());
class TourGuide {
List<GuideExtraService> guideExtraServices;
TourGuide({
this.guideExtraServices,
});
factory TourGuide.fromJson(Map<String, dynamic> json) => TourGuide(
guideExtraServices: List<GuideExtraService>.from(json["guideExtraServices"].map((x) => GuideExtraService.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"guideExtraServices": List<dynamic>.from(guideExtraServices.map((x) => x.toJson())),
};
}
class GuideExtraService {
String name;
int fees;
GuideExtraService({
this.name,
this.fees,
});
factory GuideExtraService.fromJson(Map<String, dynamic> json) => GuideExtraService(
name: json["Name"],
fees: json["Fees"],
);
Map<String, dynamic> toJson() => {
"Name": name,
"Fees": fees,
};
}
Please try the below code :-
First Create Model :-
class GuideResponseModel {
List<GuideExtraServicesModel> guideExtraServiceList;
GuideResponseModel({
this.guideExtraServiceList
});
factory GuideResponseModel.fromJson(Map<String, dynamic> parsedJson) {
try {
List<GuideExtraServicesModel> guideExtraServiceModelList = new List();
if (parsedJson.containsKey('guideExtraServices')) {
var countryList = parsedJson['guideExtraServices'] as List;
guideExtraServiceModelList =
countryList.map((i) => GuideExtraServicesModel.fromJson(i)).toList();
}
return GuideResponseModel(
guideExtraServiceList: guideExtraServiceModelList
);
} catch (e) {
return null;
}
}
}
class GuideExtraServicesModel {
String name;
int fees;
GuideExtraServicesModel({this.name,this.fees});
factory GuideExtraServicesModel.fromJson(Map<String, dynamic> json) {
return GuideExtraServicesModel(name: json['Name'],fees: json['Fees']);
}
}
Second User the Model:-
String jsonData = '{"guideExtraServices": [{"Name": "Limousine","Fees": 100},{"Name": "Bus","Fees": 10000},{"Name": "Mini-Bus","Fees": 5000}]}';
final dynamic jsonResponse = json.decode(jsonData);
final GuideResponseModel responseModel = GuideResponseModel.fromJson(jsonResponse);
print('======${responseModel.guideExtraServiceList[0].name}----${responseModel.guideExtraServiceList[0].fees}');