Exception: type 'String' is not a subtype of type 'int' - Flutter - flutter

I am trying to make a Get request in flutter.
I did everything right but it is showing me the error: type 'String' is not a sub-type of type 'int'.
I am getting error thrown on catch block saying at line 394 of Model class footerStyleType is String but i checked the json it is int.
This is my get request:
class FormDataAdp extends ChangeNotifier {
FormListModel formlist;
String formdatahttpcode = "";
resetFormDataAdp() {
formlist = null;
formdatahttpcode = "";
}
refreshdata(String token) {
resetFormDataAdp();
notifyListeners();
getFormList(token);
}
getFormList(String token) async {
try {
final url = Helper.baseURL + "form-manager-owned/10/false/all?page=1";
final client = http.Client();
final response = await client.get(Uri.parse(url), headers: {
'Authorization': 'Bearer $token',
});
print(response.body + response.statusCode.toString());
formdatahttpcode = response.statusCode.toString();
print(formdatahttpcode);
notifyListeners();
if (response.statusCode == 200) {
final parsed = jsonDecode(response.body);
formlist = FormListModel.fromJson(parsed);
notifyListeners();
return formlist;
} else {
throw Exception("Unable to fetch the data.");
}
} catch (e) {
throw Exception(e.toString());
}
}
}
This is my Model Class which i converted into dart from Json.
class FormListModel {
Forms forms;
int totalRecords;
int totalActiveForms;
FormListModel({this.forms, this.totalRecords, this.totalActiveForms});
FormListModel.fromJson(Map<String, dynamic> json) {
forms = json['forms'] != null ? new Forms.fromJson(json['forms']) : null;
totalRecords = json['total_records'];
totalActiveForms = json['total_active_forms'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.forms != null) {
data['forms'] = this.forms.toJson();
}
data['total_records'] = this.totalRecords;
data['total_active_forms'] = this.totalActiveForms;
return data;
}
}
class Forms {
int currentPage;
List<Data> data;
String firstPageUrl;
int from;
int lastPage;
String lastPageUrl;
List<Links> links;
String nextPageUrl;
String path;
int perPage;
String prevPageUrl;
int to;
int total;
Forms(
{this.currentPage,
this.data,
this.firstPageUrl,
this.from,
this.lastPage,
this.lastPageUrl,
this.links,
this.nextPageUrl,
this.path,
this.perPage,
this.prevPageUrl,
this.to,
this.total});
Forms.fromJson(Map<String, dynamic> json) {
currentPage = json['current_page'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
firstPageUrl = json['first_page_url'];
from = json['from'];
lastPage = json['last_page'];
lastPageUrl = json['last_page_url'];
if (json['links'] != null) {
links = <Links>[];
json['links'].forEach((v) {
links.add(new Links.fromJson(v));
});
}
nextPageUrl = json['next_page_url'];
path = json['path'];
perPage = json['per_page'];
prevPageUrl = json['prev_page_url'];
to = json['to'];
total = json['total'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['current_page'] = this.currentPage;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
data['first_page_url'] = this.firstPageUrl;
data['from'] = this.from;
data['last_page'] = this.lastPage;
data['last_page_url'] = this.lastPageUrl;
if (this.links != null) {
data['links'] = this.links.map((v) => v.toJson()).toList();
}
data['next_page_url'] = this.nextPageUrl;
data['path'] = this.path;
data['per_page'] = this.perPage;
data['prev_page_url'] = this.prevPageUrl;
data['to'] = this.to;
data['total'] = this.total;
return data;
}
}
class Data {
String sId;
bool fieldError;
String validationError;
List<String> rules;
bool ruleApplicable;
bool ruleConditionApplicable;
bool isDisabled;
String group;
String placeholderValue;
bool questionLabelHide;
int formId;
int id;
String label;
String guideLinesForUser;
int visibleTo;
bool isRequired;
int position;
GeneralOptionClass propertyStaticOptions;
List<GeneralOptionClass> visibleToOptions;
int page;
List<GeneralOptionClass> classificationOptions;
int classification;
String fieldName;
int alignment;
List<GeneralOptionClass> alignmentOptions;
bool isHidden;
String controlType;
bool active;
bool editownentry;
bool enableEditAfterReviewPage;
bool submitButtonDisabled;
String isUserAuthenticated;
List<String> payment;
bool enableFormFooter;
int footerType;
int footerPadding;
int footerStyleType;
String footerContent;
List<String> relationships;
List<String> formRules;
bool enableSaveAndResumeLater;
int fieldSize;
int fieldHeight;
bool headerDeleted;
PageNavigator pageNavigator;
bool enableClientLogin;
int entriesCount;
int clientLoginWith;
List<GeneralOptionClass> clientLoginWithOptions;
bool enableReviewPage;
String reviewPageTitle;
String reviewPageDescription;
int buttonStyle;
List<GeneralOptionClass> buttonStyleOptions;
String submitButtonText;
String backButtonText;
String submitButtonImageURL;
String backButtonImageURL;
bool enablePasswordProtection;
String password;
bool enableSpamProtection;
int spamType;
List<GeneralOptionClass> spamTypeOptions;
bool limitOneEntryPerIP;
bool limitOneEntryPerUserId;
bool limitEntries;
int maxEntriesLimit;
bool enableAutomaticScheduling;
int timeOption;
List<GeneralOptionClass> timeOptions;
int formType;
List<GeneralOptionClass> formTypes;
String scheduleFromDate;
String scheduleToDate;
int dateFormat;
List<GeneralOptionClass> footerTypeOptions;
String footerImageUrl;
int footerImageheight;
int footerImagewidth;
List<GeneralOptionClass> footerStyleTypeOptions;
bool isTemplate;
bool redirectionSet;
String redirecturl;
String redirectionMsg;
bool redirectPostConfirmation;
bool showtitledesc;
String createdBy;
String updatedBy;
bool showTimer;
int leftTime;
int notifyBefore;
bool showInternalUsers;
bool showTimerNotification;
String timerNotificationMessage;
bool demandTimerStart;
int demandTimerPage;
bool enableAutoSubmitWithTimer;
String defaultSaveNResumeEmailSubject;
List<FieldRules> fieldRules;
bool negativeMarking;
int negationPercentage;
List<GeneralOptionClass> fieldSizeOptions;
String clientid;
bool published;
String updatedAt;
String createdAt;
String createdByName;
List<Permissions> permissions;
int pendingAprovalCount;
CreatedView createdView;
List<String> sharedWith;
Data(
{this.sId,
this.fieldError,
this.validationError,
this.rules,
this.ruleApplicable,
this.ruleConditionApplicable,
this.isDisabled,
this.group,
this.placeholderValue,
this.questionLabelHide,
this.formId,
this.id,
this.label,
this.guideLinesForUser,
this.visibleTo,
this.isRequired,
this.position,
this.propertyStaticOptions,
this.visibleToOptions,
this.page,
this.classificationOptions,
this.classification,
this.fieldName,
this.alignment,
this.alignmentOptions,
this.isHidden,
this.controlType,
this.active,
this.editownentry,
this.enableEditAfterReviewPage,
this.submitButtonDisabled,
this.isUserAuthenticated,
this.payment,
this.enableFormFooter,
this.footerType,
this.footerPadding,
this.footerStyleType,
this.footerContent,
this.relationships,
this.formRules,
this.enableSaveAndResumeLater,
this.fieldSize,
this.fieldHeight,
this.headerDeleted,
this.pageNavigator,
this.enableClientLogin,
this.entriesCount,
this.clientLoginWith,
this.clientLoginWithOptions,
this.enableReviewPage,
this.reviewPageTitle,
this.reviewPageDescription,
this.buttonStyle,
this.buttonStyleOptions,
this.submitButtonText,
this.backButtonText,
this.submitButtonImageURL,
this.backButtonImageURL,
this.enablePasswordProtection,
this.password,
this.enableSpamProtection,
this.spamType,
this.spamTypeOptions,
this.limitOneEntryPerIP,
this.limitOneEntryPerUserId,
this.limitEntries,
this.maxEntriesLimit,
this.enableAutomaticScheduling,
this.timeOption,
this.timeOptions,
this.formType,
this.formTypes,
this.scheduleFromDate,
this.scheduleToDate,
this.dateFormat,
this.footerTypeOptions,
this.footerImageUrl,
this.footerImageheight,
this.footerImagewidth,
this.footerStyleTypeOptions,
this.isTemplate,
this.redirectionSet,
this.redirecturl,
this.redirectionMsg,
this.redirectPostConfirmation,
this.showtitledesc,
this.createdBy,
this.updatedBy,
this.showTimer,
this.leftTime,
this.notifyBefore,
this.showInternalUsers,
this.showTimerNotification,
this.timerNotificationMessage,
this.demandTimerStart,
this.demandTimerPage,
this.enableAutoSubmitWithTimer,
this.defaultSaveNResumeEmailSubject,
this.fieldRules,
this.negativeMarking,
this.negationPercentage,
this.fieldSizeOptions,
this.clientid,
this.published,
this.updatedAt,
this.createdAt,
this.createdByName,
this.permissions,
this.pendingAprovalCount,
this.createdView,
this.sharedWith});
Data.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
fieldError = json['fieldError'];
validationError = json['validationError'];
if (json['rules'] != null) {
rules = <String>[];
json['rules'].forEach((v) {
rules.add(v);
});
}
ruleApplicable = json['ruleApplicable'];
ruleConditionApplicable = json['ruleConditionApplicable'];
isDisabled = json['isDisabled'];
group = json['group'];
placeholderValue = json['placeholderValue'];
questionLabelHide = json['questionLabelHide'];
formId = json['form_id'];
id = json['id'];
label = json['label'];
guideLinesForUser = json['guideLinesForUser'];
visibleTo = json['visibleTo'];
isRequired = json['isRequired'];
position = json['position'];
propertyStaticOptions = json['propertyStaticOptions'] != null
? new GeneralOptionClass.fromJson(json['propertyStaticOptions'])
: null;
if (json['visibleToOptions'] != null) {
visibleToOptions = <GeneralOptionClass>[];
json['visibleToOptions'].forEach((v) {
visibleToOptions.add(new GeneralOptionClass.fromJson(v));
});
}
page = json['page'];
if (json['classificationOptions'] != null) {
classificationOptions = <GeneralOptionClass>[];
json['classificationOptions'].forEach((v) {
classificationOptions.add(new GeneralOptionClass.fromJson(v));
});
}
classification = json['classification'];
fieldName = json['fieldName'];
alignment = json['alignment'];
if (json['alignmentOptions'] != null) {
alignmentOptions = <GeneralOptionClass>[];
json['alignmentOptions'].forEach((v) {
alignmentOptions.add(new GeneralOptionClass.fromJson(v));
});
}
isHidden = json['isHidden'];
controlType = json['controlType'];
active = json['active'];
editownentry = json['editownentry'];
enableEditAfterReviewPage = json['enableEditAfterReviewPage'];
submitButtonDisabled = json['submitButtonDisabled'];
isUserAuthenticated = json['isUserAuthenticated'];
if (json['payment'] != null) {
payment = <String>[];
json['payment'].forEach((v) {
payment.add(v);
});
}
enableFormFooter = json['enableFormFooter'];
footerType = json['footerType'];
footerPadding = json['footerPadding'];
footerStyleType = json['footerStyleType'];
footerContent = json['footerContent'];
if (json['relationships'] != null) {
relationships = <String>[];
json['relationships'].forEach((v) {
relationships.add(v);
});
}
if (json['formRules'] != null) {
formRules = <String>[];
json['formRules'].forEach((v) {
formRules.add(v);
});
}
enableSaveAndResumeLater = json['enableSaveAndResumeLater'];
fieldSize = json['fieldSize'];
fieldHeight = json['fieldHeight'];
headerDeleted = json['headerDeleted'];
pageNavigator = json['pageNavigator'] != null
? new PageNavigator.fromJson(json['pageNavigator'])
: null;
enableClientLogin = json['enableClientLogin'];
entriesCount = json['entriesCount'];
clientLoginWith = json['clientLoginWith'];
if (json['clientLoginWithOptions'] != null) {
clientLoginWithOptions = <GeneralOptionClass>[];
json['clientLoginWithOptions'].forEach((v) {
clientLoginWithOptions.add(new GeneralOptionClass.fromJson(v));
});
}
enableReviewPage = json['enableReviewPage'];
reviewPageTitle = json['reviewPageTitle'];
reviewPageDescription = json['reviewPageDescription'];
buttonStyle = json['buttonStyle'];
if (json['buttonStyleOptions'] != null) {
buttonStyleOptions = <GeneralOptionClass>[];
json['buttonStyleOptions'].forEach((v) {
buttonStyleOptions.add(new GeneralOptionClass.fromJson(v));
});
}
submitButtonText = json['submitButtonText'];
backButtonText = json['backButtonText'];
submitButtonImageURL = json['submitButtonImageURL'];
backButtonImageURL = json['backButtonImageURL'];
enablePasswordProtection = json['enablePasswordProtection'];
password = json['password'];
enableSpamProtection = json['enableSpamProtection'];
spamType = json['spamType'];
if (json['spamTypeOptions'] != null) {
spamTypeOptions = <GeneralOptionClass>[];
json['spamTypeOptions'].forEach((v) {
spamTypeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
limitOneEntryPerIP = json['limitOneEntryPerIP'];
limitOneEntryPerUserId = json['limitOneEntryPerUserId'];
limitEntries = json['limitEntries'];
maxEntriesLimit = json['maxEntriesLimit'];
enableAutomaticScheduling = json['enableAutomaticScheduling'];
timeOption = json['timeOption'];
if (json['timeOptions'] != null) {
timeOptions = <GeneralOptionClass>[];
json['timeOptions'].forEach((v) {
timeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
formType = json['formType'];
if (json['formTypes'] != null) {
formTypes = <GeneralOptionClass>[];
json['formTypes'].forEach((v) {
formTypes.add(new GeneralOptionClass.fromJson(v));
});
}
scheduleFromDate = json['scheduleFromDate'];
scheduleToDate = json['scheduleToDate'];
dateFormat = json['dateFormat'];
if (json['footerTypeOptions'] != null) {
footerTypeOptions = <GeneralOptionClass>[];
json['footerTypeOptions'].forEach((v) {
footerTypeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
footerImageUrl = json['footerImageUrl'];
footerImageheight = json['footerImageheight'];
footerImagewidth = json['footerImagewidth'];
if (json['footerStyleTypeOptions'] != null) {
footerStyleTypeOptions = <GeneralOptionClass>[];
json['footerStyleTypeOptions'].forEach((v) {
footerStyleTypeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
isTemplate = json['isTemplate'];
redirectionSet = json['redirectionSet'];
redirecturl = json['redirecturl'];
redirectionMsg = json['redirectionMsg'];
redirectPostConfirmation = json['redirectPostConfirmation'];
showtitledesc = json['showtitledesc'];
createdBy = json['createdBy'];
updatedBy = json['updatedBy'];
showTimer = json['showTimer'];
leftTime = json['leftTime'];
notifyBefore = json['notifyBefore'];
showInternalUsers = json['showInternalUsers'];
showTimerNotification = json['showTimerNotification'];
timerNotificationMessage = json['timerNotificationMessage'];
demandTimerStart = json['demandTimerStart'];
demandTimerPage = json['demandTimerPage'];
enableAutoSubmitWithTimer = json['enableAutoSubmitWithTimer'];
defaultSaveNResumeEmailSubject = json['defaultSaveNResumeEmailSubject'];
if (json['fieldRules'] != null) {
fieldRules = <FieldRules>[];
json['fieldRules'].forEach((v) {
fieldRules.add(new FieldRules.fromJson(v));
});
}
negativeMarking = json['negativeMarking'];
negationPercentage = json['negationPercentage'];
if (json['fieldSizeOptions'] != null) {
fieldSizeOptions = <GeneralOptionClass>[];
json['fieldSizeOptions'].forEach((v) {
fieldSizeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
clientid = json['clientid'];
published = json['published'];
updatedAt = json['updated_at'];
createdAt = json['created_at'];
createdByName = json['createdByName'];
if (json['permissions'] != null) {
permissions = <Permissions>[];
json['permissions'].forEach((v) {
permissions.add(new Permissions.fromJson(v));
});
}
pendingAprovalCount = json['pendingAprovalCount'];
createdView = json['created_view'] != null
? new CreatedView.fromJson(json['created_view'])
: null;
sharedWith = json['sharedWith'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['fieldError'] = this.fieldError;
data['validationError'] = this.validationError;
// if (this.rules != null) {
// data['rules'] = this.rules.map((v) => v.toJson()).toList();
// }
data['ruleApplicable'] = this.ruleApplicable;
data['ruleConditionApplicable'] = this.ruleConditionApplicable;
data['isDisabled'] = this.isDisabled;
data['group'] = this.group;
data['placeholderValue'] = this.placeholderValue;
data['questionLabelHide'] = this.questionLabelHide;
data['form_id'] = this.formId;
data['id'] = this.id;
data['label'] = this.label;
data['guideLinesForUser'] = this.guideLinesForUser;
data['visibleTo'] = this.visibleTo;
data['isRequired'] = this.isRequired;
data['position'] = this.position;
if (this.propertyStaticOptions != null) {
data['propertyStaticOptions'] = this.propertyStaticOptions.toJson();
}
if (this.visibleToOptions != null) {
data['visibleToOptions'] =
this.visibleToOptions.map((v) => v.toJson()).toList();
}
data['page'] = this.page;
if (this.classificationOptions != null) {
data['classificationOptions'] =
this.classificationOptions.map((v) => v.toJson()).toList();
}
data['classification'] = this.classification;
data['fieldName'] = this.fieldName;
data['alignment'] = this.alignment;
if (this.alignmentOptions != null) {
data['alignmentOptions'] =
this.alignmentOptions.map((v) => v.toJson()).toList();
}
data['isHidden'] = this.isHidden;
data['controlType'] = this.controlType;
data['active'] = this.active;
data['editownentry'] = this.editownentry;
data['enableEditAfterReviewPage'] = this.enableEditAfterReviewPage;
data['submitButtonDisabled'] = this.submitButtonDisabled;
data['isUserAuthenticated'] = this.isUserAuthenticated;
// if (this.payment != null) {
// data['payment'] = this.payment.map((v) => v.toJson()).toList();
// }
data['enableFormFooter'] = this.enableFormFooter;
data['footerType'] = this.footerType;
data['footerPadding'] = this.footerPadding;
data['footerStyleType'] = this.footerStyleType;
data['footerContent'] = this.footerContent;
// if (this.relationships != null) {
// data['relationships'] =
// this.relationships.map((v) => v.toJson()).toList();
// }
// if (this.formRules != null) {
// data['formRules'] = this.formRules.map((v) => v.toJson()).toList();
// }
data['enableSaveAndResumeLater'] = this.enableSaveAndResumeLater;
data['fieldSize'] = this.fieldSize;
data['fieldHeight'] = this.fieldHeight;
data['headerDeleted'] = this.headerDeleted;
if (this.pageNavigator != null) {
data['pageNavigator'] = this.pageNavigator.toJson();
}
data['enableClientLogin'] = this.enableClientLogin;
data['entriesCount'] = this.entriesCount;
data['clientLoginWith'] = this.clientLoginWith;
if (this.clientLoginWithOptions != null) {
data['clientLoginWithOptions'] =
this.clientLoginWithOptions.map((v) => v.toJson()).toList();
}
data['enableReviewPage'] = this.enableReviewPage;
data['reviewPageTitle'] = this.reviewPageTitle;
data['reviewPageDescription'] = this.reviewPageDescription;
data['buttonStyle'] = this.buttonStyle;
if (this.buttonStyleOptions != null) {
data['buttonStyleOptions'] =
this.buttonStyleOptions.map((v) => v.toJson()).toList();
}
data['submitButtonText'] = this.submitButtonText;
data['backButtonText'] = this.backButtonText;
data['submitButtonImageURL'] = this.submitButtonImageURL;
data['backButtonImageURL'] = this.backButtonImageURL;
data['enablePasswordProtection'] = this.enablePasswordProtection;
data['password'] = this.password;
data['enableSpamProtection'] = this.enableSpamProtection;
data['spamType'] = this.spamType;
if (this.spamTypeOptions != null) {
data['spamTypeOptions'] =
this.spamTypeOptions.map((v) => v.toJson()).toList();
}
data['limitOneEntryPerIP'] = this.limitOneEntryPerIP;
data['limitOneEntryPerUserId'] = this.limitOneEntryPerUserId;
data['limitEntries'] = this.limitEntries;
data['maxEntriesLimit'] = this.maxEntriesLimit;
data['enableAutomaticScheduling'] = this.enableAutomaticScheduling;
data['timeOption'] = this.timeOption;
if (this.timeOptions != null) {
data['timeOptions'] = this.timeOptions.map((v) => v.toJson()).toList();
}
data['formType'] = this.formType;
if (this.formTypes != null) {
data['formTypes'] = this.formTypes.map((v) => v.toJson()).toList();
}
data['scheduleFromDate'] = this.scheduleFromDate;
data['scheduleToDate'] = this.scheduleToDate;
data['dateFormat'] = this.dateFormat;
if (this.footerTypeOptions != null) {
data['footerTypeOptions'] =
this.footerTypeOptions.map((v) => v.toJson()).toList();
}
data['footerImageUrl'] = this.footerImageUrl;
data['footerImageheight'] = this.footerImageheight;
data['footerImagewidth'] = this.footerImagewidth;
if (this.footerStyleTypeOptions != null) {
data['footerStyleTypeOptions'] =
this.footerStyleTypeOptions.map((v) => v.toJson()).toList();
}
data['isTemplate'] = this.isTemplate;
data['redirectionSet'] = this.redirectionSet;
data['redirecturl'] = this.redirecturl;
data['redirectionMsg'] = this.redirectionMsg;
data['redirectPostConfirmation'] = this.redirectPostConfirmation;
data['showtitledesc'] = this.showtitledesc;
data['createdBy'] = this.createdBy;
data['updatedBy'] = this.updatedBy;
data['showTimer'] = this.showTimer;
data['leftTime'] = this.leftTime;
data['notifyBefore'] = this.notifyBefore;
data['showInternalUsers'] = this.showInternalUsers;
data['showTimerNotification'] = this.showTimerNotification;
data['timerNotificationMessage'] = this.timerNotificationMessage;
data['demandTimerStart'] = this.demandTimerStart;
data['demandTimerPage'] = this.demandTimerPage;
data['enableAutoSubmitWithTimer'] = this.enableAutoSubmitWithTimer;
data['defaultSaveNResumeEmailSubject'] =
this.defaultSaveNResumeEmailSubject;
if (this.fieldRules != null) {
data['fieldRules'] = this.fieldRules.map((v) => v.toJson()).toList();
}
data['negativeMarking'] = this.negativeMarking;
data['negationPercentage'] = this.negationPercentage;
if (this.fieldSizeOptions != null) {
data['fieldSizeOptions'] =
this.fieldSizeOptions.map((v) => v.toJson()).toList();
}
data['clientid'] = this.clientid;
data['published'] = this.published;
data['updated_at'] = this.updatedAt;
data['created_at'] = this.createdAt;
data['createdByName'] = this.createdByName;
if (this.permissions != null) {
data['permissions'] = this.permissions.map((v) => v.toJson()).toList();
}
data['pendingAprovalCount'] = this.pendingAprovalCount;
if (this.createdView != null) {
data['created_view'] = this.createdView.toJson();
}
data['sharedWith'] = this.sharedWith;
return data;
}
}
class GeneralOptionClass {
int id;
String option;
GeneralOptionClass({this.id, this.option});
GeneralOptionClass.fromJson(Map<String, dynamic> json) {
id = json['id'];
option = json['option'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['option'] = this.option;
return data;
}
}
}
I debugged also but it is still same. Please help. If you have any questions please ask.

Related

Not properly mapping values in Dart model

I know I am not properly mapping values when it comes to make a GET request since I am getting a null response.
Specifically I know the problem it is the fields "Behavior" and "Description" since they are lists and are more complex to map for me. Before adding these two fields the mapping was done properly and I was able to get the proper response.
my fetchdata function:
fetchData(url) async {
var client = http.Client();
final response = await client.get(Uri.parse(url));
if (response.statusCode == 200) {
var jsonDecoded = json.decode(response.body);
BreedList = jsonDecoded.map((data) => DogClass.fromJson(data)).toList();
return jsonDecoded;
} else {
throw Exception('Failed to load data');
}
}
Here I am attaching my data model.
class DogClass {
Id? _iId;
String? _breed;
String? _origin;
String? _url;
String? _img;
List<Behavior>? _behavior;
List<Description>? _description;
final _descriptionlist = <Description>[];
DogClass(
{Id? iId,
String? breed,
String? origin,
String? url,
String? img,
List<Behavior>? behavior,
List<Description>? description}) {
if (iId != null) {
this._iId = iId;
}
if (breed != null) {
this._breed = breed;
}
if (origin != null) {
this._origin = origin;
}
if (url != null) {
this._url = url;
}
if (img != null) {
this._img = img;
}
if (behavior != null) {
this._behavior = behavior;
}
if (description != null) {
this._description = description;
}
}
Id? get iId => _iId;
set iId(Id? iId) => _iId = iId;
String? get breed => _breed;
set breed(String? breed) => _breed = breed;
String? get origin => _origin;
set origin(String? origin) => _origin = origin;
String? get url => _url;
set url(String? url) => _url = url;
String? get img => _img;
set img(String? img) => _img = img;
List<Behavior>? get behavior => _behavior;
set behavior(List<Behavior>? behavior) => _behavior = behavior;
List<Description>? get description => _description;
set description(List<Description>? description) => _description = description;
factory DogClass.fromJson(Map<String, dynamic> json) {
return DogClass(
iId: json['_id'] != null ? Id.fromJson(json['_id']) : null,
breed: json['breed'],
origin: json['origin'],
url: json['url'],
img: json['img'],
behavior: (json['behavior'] as List).cast<Behavior>(),
description: (json['Description'] as List).cast<Description>());
}
}
class Id {
String? _oid;
Id({String? oid}) {
if (oid != null) {
this._oid = oid;
}
}
String? get oid => _oid;
set oid(String? oid) => _oid = oid;
Id.fromJson(Map<String, dynamic> json) {
_oid = json['$oid'];
}
}
class Behavior {
Id? _iId;
String? _imageLink;
int? _goodWithChildren;
int? _goodWithOtherDogs;
int? _shedding;
int? _grooming;
int? _drooling;
int? _coatLength;
int? _goodWithStrangers;
int? _playfulness;
int? _protectiveness;
int? _trainability;
int? _energy;
int? _barking;
int? _minLifeExpectancy;
int? _maxLifeExpectancy;
double? _maxHeightMale;
double? _maxHeightFemale;
int? _maxWeightMale;
int? _maxWeightFemale;
int? _minHeightMale;
int? _minHeightFemale;
int? _minWeightMale;
int? _minWeightFemale;
String? _breed;
Behavior(
{Id? iId,
String? imageLink,
int? goodWithChildren,
int? goodWithOtherDogs,
int? shedding,
int? grooming,
int? drooling,
int? coatLength,
int? goodWithStrangers,
int? playfulness,
int? protectiveness,
int? trainability,
int? energy,
int? barking,
int? minLifeExpectancy,
int? maxLifeExpectancy,
double? maxHeightMale,
double? maxHeightFemale,
int? maxWeightMale,
int? maxWeightFemale,
int? minHeightMale,
int? minHeightFemale,
int? minWeightMale,
int? minWeightFemale,
String? breed}) {
if (iId != null) {
this._iId = iId;
}
if (imageLink != null) {
this._imageLink = imageLink;
}
if (goodWithChildren != null) {
this._goodWithChildren = goodWithChildren;
}
if (goodWithOtherDogs != null) {
this._goodWithOtherDogs = goodWithOtherDogs;
}
if (shedding != null) {
this._shedding = shedding;
}
if (grooming != null) {
this._grooming = grooming;
}
if (drooling != null) {
this._drooling = drooling;
}
if (coatLength != null) {
this._coatLength = coatLength;
}
if (goodWithStrangers != null) {
this._goodWithStrangers = goodWithStrangers;
}
if (playfulness != null) {
this._playfulness = playfulness;
}
if (protectiveness != null) {
this._protectiveness = protectiveness;
}
if (trainability != null) {
this._trainability = trainability;
}
if (energy != null) {
this._energy = energy;
}
if (barking != null) {
this._barking = barking;
}
if (minLifeExpectancy != null) {
this._minLifeExpectancy = minLifeExpectancy;
}
if (maxLifeExpectancy != null) {
this._maxLifeExpectancy = maxLifeExpectancy;
}
if (maxHeightMale != null) {
this._maxHeightMale = maxHeightMale;
}
if (maxHeightFemale != null) {
this._maxHeightFemale = maxHeightFemale;
}
if (maxWeightMale != null) {
this._maxWeightMale = maxWeightMale;
}
if (maxWeightFemale != null) {
this._maxWeightFemale = maxWeightFemale;
}
if (minHeightMale != null) {
this._minHeightMale = minHeightMale;
}
if (minHeightFemale != null) {
this._minHeightFemale = minHeightFemale;
}
if (minWeightMale != null) {
this._minWeightMale = minWeightMale;
}
if (minWeightFemale != null) {
this._minWeightFemale = minWeightFemale;
}
if (breed != null) {
this._breed = breed;
}
}
Id? get iId => _iId;
set iId(Id? iId) => _iId = iId;
String? get imageLink => _imageLink;
set imageLink(String? imageLink) => _imageLink = imageLink;
int? get goodWithChildren => _goodWithChildren;
set goodWithChildren(int? goodWithChildren) =>
_goodWithChildren = goodWithChildren;
int? get goodWithOtherDogs => _goodWithOtherDogs;
set goodWithOtherDogs(int? goodWithOtherDogs) =>
_goodWithOtherDogs = goodWithOtherDogs;
int? get shedding => _shedding;
set shedding(int? shedding) => _shedding = shedding;
int? get grooming => _grooming;
set grooming(int? grooming) => _grooming = grooming;
int? get drooling => _drooling;
set drooling(int? drooling) => _drooling = drooling;
int? get coatLength => _coatLength;
set coatLength(int? coatLength) => _coatLength = coatLength;
int? get goodWithStrangers => _goodWithStrangers;
set goodWithStrangers(int? goodWithStrangers) =>
_goodWithStrangers = goodWithStrangers;
int? get playfulness => _playfulness;
set playfulness(int? playfulness) => _playfulness = playfulness;
int? get protectiveness => _protectiveness;
set protectiveness(int? protectiveness) => _protectiveness = protectiveness;
int? get trainability => _trainability;
set trainability(int? trainability) => _trainability = trainability;
int? get energy => _energy;
set energy(int? energy) => _energy = energy;
int? get barking => _barking;
set barking(int? barking) => _barking = barking;
int? get minLifeExpectancy => _minLifeExpectancy;
set minLifeExpectancy(int? minLifeExpectancy) =>
_minLifeExpectancy = minLifeExpectancy;
int? get maxLifeExpectancy => _maxLifeExpectancy;
set maxLifeExpectancy(int? maxLifeExpectancy) =>
_maxLifeExpectancy = maxLifeExpectancy;
double? get maxHeightMale => _maxHeightMale;
set maxHeightMale(double? maxHeightMale) => _maxHeightMale = maxHeightMale;
double? get maxHeightFemale => _maxHeightFemale;
set maxHeightFemale(double? maxHeightFemale) =>
_maxHeightFemale = maxHeightFemale;
int? get maxWeightMale => _maxWeightMale;
set maxWeightMale(int? maxWeightMale) => _maxWeightMale = maxWeightMale;
int? get maxWeightFemale => _maxWeightFemale;
set maxWeightFemale(int? maxWeightFemale) =>
_maxWeightFemale = maxWeightFemale;
int? get minHeightMale => _minHeightMale;
set minHeightMale(int? minHeightMale) => _minHeightMale = minHeightMale;
int? get minHeightFemale => _minHeightFemale;
set minHeightFemale(int? minHeightFemale) =>
_minHeightFemale = minHeightFemale;
int? get minWeightMale => _minWeightMale;
set minWeightMale(int? minWeightMale) => _minWeightMale = minWeightMale;
int? get minWeightFemale => _minWeightFemale;
set minWeightFemale(int? minWeightFemale) =>
_minWeightFemale = minWeightFemale;
String? get breed => _breed;
set breed(String? breed) => _breed = breed;
factory Behavior.fromJson(Map<String, dynamic> json) {
return Behavior(
iId : json['_id'] != null ? Id.fromJson(json['_id']) : null,
imageLink : json['image_link'],
goodWithChildren : json['good_with_children'],
goodWithOtherDogs : json['good_with_other_dogs'],
shedding : json['shedding'],
grooming : json['grooming'],
drooling : json['drooling'],
coatLength : json['coat_length'],
goodWithStrangers : json['good_with_strangers'],
playfulness : json['playfulness'],
protectiveness : json['protectiveness'],
trainability : json['trainability'],
energy : json['energy'],
barking : json['barking'],
minLifeExpectancy : json['min_life_expectancy'],
maxLifeExpectancy : json['max_life_expectancy'],
maxHeightMale : json['max_height_male'],
maxHeightFemale : json['max_height_female'],
maxWeightMale : json['max_weight_male'],
maxWeightFemale : json['max_weight_female'],
minHeightMale : json['min_height_male'],
minHeightFemale : json['min_height_female'],
minWeightMale : json['min_weight_male'],
minWeightFemale : json['min_weight_female'],
breed : json['breed']
);}
}
class Description {
Id? iId;
String? breed;
String? contenido;
Description({this.iId, this.breed, this.contenido});
factory Description.fromJson(Map<String, dynamic> json) {
return Description(
iId: json['_id'] != null ? Id.fromJson(json['_id']) : null,
breed: json['breed'],
contenido: json['contenido'],
);
}
}
Here's is my json content:
[{"_id": {"$oid": "625f2900fe6aeb351381c3f5"}, "breed": "Africanis", "origin": "Southern Africa", "url": "https://en.wikipedia.org/wiki/Af", "img": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/", "behavior": [], "Description": [{"_id": {"$oid": "626829de7103fd0096bd5dd8"}, "breed": "Africanis", "contenido": "Some content"}]}
Any help would be really appreciated.
I prefer you to use a vs code tool to easily make a dart data model
Name: Json to Dart Model
VS Marketplace Link:
https://marketplace.visualstudio.com/items?itemName=hirantha.json-to-dart
Here is the model code, You just pass GET response data through it
class DogClass {
Id? id;
String? breed;
String? origin;
String? url;
String? img;
List<dynamic>? behavior;
List<Description>? description;
DogClass({
this.id,
this.breed,
this.origin,
this.url,
this.img,
this.behavior,
this.description,
});
factory DogClass.fromMap(Map<String, dynamic> data) => DogClass(
id: data['_id'] == null
? null
: Id.fromMap(data['_id'] as Map<String, dynamic>),
breed: data['breed'] as String?,
origin: data['origin'] as String?,
url: data['url'] as String?,
img: data['img'] as String?,
behavior: data['behavior'] as List<dynamic>?,
description: (data['Description'] as List<dynamic>?)
?.map((e) => Description.fromMap(e as Map<String, dynamic>))
.toList(),
);
}
/// id DogClass class
///
class Id {
String? oid;
Id({this.oid});
factory Id.fromMap(Map<String, dynamic> data) => Id(
oid: data['\$oid'] as String?,
);
}
// description class DogClass
//
class Description {
Id? id;
String? breed;
String? contenido;
Description({this.id, this.breed, this.contenido});
factory Description.fromMap(Map<String, dynamic> data) => Description(
id: data['_id'] == null
? null
: Id.fromMap(data['_id'] as Map<String, dynamic>),
breed: data['breed'] as String?,
contenido: data['contenido'] as String?,
);
}

Flutter - How to show data from Model 1 and data from Model2 in one UI

I successfully called http cho the ProductModel and now i dont know how to get the ProductDrugModel to show along with ProductModel
this is my Model1:
class ProductModel {
String productID;
String drugbankID;
String productName;
String productLabeller;
String productCode;
String productRoute;
String productStrength;
String productdosage;
String approved;
String otc;
String generic;
String country;
ProductModel(
{this.productID,
this.drugbankID,
this.productName,
this.productLabeller,
this.productCode,
this.productRoute,
this.productStrength,
this.productdosage,
this.approved,
this.otc,
this.generic,
this.country});
ProductModel.fromJson(Map<String, dynamic> json) {
productID = json['productID'];
drugbankID = json['drugbankID'];
productName = json['productName'];
productLabeller = json['productLabeller'];
productCode = json['productCode'];
productRoute = json['productRoute'];
productStrength = json['productStrength'];
productdosage = json['productdosage'];
approved = json['approved'];
otc = json['otc'];
generic = json['generic'];
country = json['country'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['productID'] = this.productID;
data['drugbankID'] = this.drugbankID;
data['productName'] = this.productName;
data['productLabeller'] = this.productLabeller;
data['productCode'] = this.productCode;
data['productRoute'] = this.productRoute;
data['productStrength'] = this.productStrength;
data['productdosage'] = this.productdosage;
data['approved'] = this.approved;
data['otc'] = this.otc;
data['generic'] = this.generic;
data['country'] = this.country;
return data;
}
}
Model2:
class ProductDrugModel {
String drugbankID;
String drugName;
String drugDescription;
String drugState;
String drugIndication;
String drugPharmaco;
String drugMechan;
String drugToxicity;
String drugMetabolism;
String drugHalflife;
String drugElimination;
String drugClearance;
ProductDrugModel({
this.drugbankID,
this.drugName,
this.drugDescription,
this.drugState,
this.drugIndication,
this.drugPharmaco,
this.drugMechan,
this.drugToxicity,
this.drugMetabolism,
this.drugHalflife,
this.drugElimination,
this.drugClearance,
});
factory ProductDrugModel.fromJson(Map<String, dynamic> json) {
return ProductDrugModel(
drugbankID: json['drugbank_ID'],
drugName: json['drugName'],
drugDescription: json['drugDescription'],
drugState: json['drugState'],
drugIndication: json['drugIndication'],
drugPharmaco: json['drugPharmaco'],
drugMechan: json['drugMechan'],
drugToxicity: json['drugToxicity'],
drugMetabolism: json['drugMetabolism'],
drugHalflife: json['drugHalflife'],
drugElimination: json['drugElimination'],
drugClearance: json['drugClearance'],
);
}
}
My api call
class RecommenedData {
static Future<List<ProductModel>> getRecommened() async {
try {
var response =
await
http.get(Uri.parse(Constants.PRODUCT_RECOMMENDED_TOP_10));
if (response.statusCode == 200) {
List listTrend = json.decode(response.body) as List;
return listTrend.map((e) =>
ProductModel.fromJson(e)).toList();
} else {
throw Exception("Failed to fetch data");
}
} catch (e) {
throw Exception("No Internet Connection");
}
}
}
ProductDrugModel
This is how i get the ProductDrugModel object
THe input will be from ProductModel drugbankID
class ProductDrugInfoService {
static Future<List<ProductDrugModel>> getProductDrugInfo(String input) async {
try {
var response =
await http.get(Uri.parse(Constants.PRODUCT_DRUG_INFOR + input));
if (response.statusCode == 200) {
List listTrend = json.decode(response.body) as List;
return listTrend.map((e) => ProductDrugModel.fromJson(e)).toList();
} else {
throw Exception("Failed to fetch data");
}
} catch (e) {
throw Exception("No Internet Connection");
}
}
}
I want to get data from ProductDrugModel by pass the drugbankID to endponit url
then show that data to the UI along with ProductModel
Any suggestion ??
Please help ><

Sort the list by date time with latest on the top in flutter app

class Order {
String id;
List<FoodOrder> foodOrders;
OrderStatus orderStatus;
double tax;
double deliveryFee;
String hint;
bool active;
DateTime dateTime;
User user;
Payment payment;
Address deliveryAddress;
Order();
Order.fromJSON(Map<String, dynamic> jsonMap) {
try {
id = jsonMap['id'].toString();
tax = jsonMap['tax'] != null ? jsonMap['tax'].toDouble() : 0.0;
deliveryFee = jsonMap['delivery_fee'] != null ? jsonMap['delivery_fee'].toDouble() : 0.0;
hint = jsonMap['hint'] != null ? jsonMap['hint'].toString() : '';
active = jsonMap['active'] ?? false;
orderStatus = jsonMap['order_status'] != null ? OrderStatus.fromJSON(jsonMap['order_status']) : OrderStatus.fromJSON({});
dateTime = DateTime.parse(jsonMap['updated_at']);
user = jsonMap['user'] != null ? User.fromJSON(jsonMap['user']) : User.fromJSON({});
deliveryAddress = jsonMap['delivery_address'] != null ? Address.fromJSON(jsonMap['delivery_address']) : Address.fromJSON({});
payment = jsonMap['payment'] != null ? Payment.fromJSON(jsonMap['payment']) : Payment.fromJSON({});
foodOrders = jsonMap['food_orders'] != null ? List.from(jsonMap['food_orders']).map((element) => FoodOrder.fromJSON(element)).toList() : [];
} catch (e) {
id = '';
tax = 0.0;
deliveryFee = 0.0;
hint = '';
active = false;
orderStatus = OrderStatus.fromJSON({});
dateTime = DateTime(0);
user = User.fromJSON({});
payment = Payment.fromJSON({});
deliveryAddress = Address.fromJSON({});
foodOrders = [];
print(CustomTrace(StackTrace.current, message: e));
}
}
Map toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["user_id"] = user?.id;
map["order_status_id"] = orderStatus?.id;
map["tax"] = tax;
map['hint'] = hint;
map["delivery_fee"] = deliveryFee;
map["foods"] = foodOrders?.map((element) => element.toMap())?.toList();
map["payment"] = payment?.toMap();
if (!deliveryAddress.isUnknown()) {
map["delivery_address_id"] = deliveryAddress?.id;
}
return map;
}
Map cancelMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
if (orderStatus?.id != null && orderStatus?.id == '1') map["active"] = false;
return map;
}
bool canCancelOrder() {
return this.active == true && this.orderStatus.id == '1'; // 1 for order received status
}
}
**I have bought this app from envato and now I want to make some changes in the design and layout. This is code snippet from a food delivery app. I want to sort the order by date time with the latest order on the top. currently they are sorted as the latest order is being displayed on the last **
If you have a list of orders you can use the sort method of List and the compareTo of DateTime to sort your orders.
// Sorts in descending order
orders.sort((Order a, Order b) => b.dateTime.compareTo(a.dateTime);

Dart : Convert From Iterable<ActivityModel> To ActivityModel

I have model Like This :
Model
class ActivityModel {
String idActivity;
String titleActivity;
String dateTimeActivity;
int isDoneActivity;
int codeIconActivity;
String informationActivity;
String createdDateActivity;
ActivityModel({
this.idActivity,
this.titleActivity,
this.dateTimeActivity,
this.isDoneActivity,
this.codeIconActivity,
this.informationActivity,
this.createdDateActivity,
});
ActivityModel.fromSqflite(Map<String, dynamic> map)
: idActivity = map['id_activity'],
titleActivity = map['title_activity'],
dateTimeActivity = map['datetime_activity'],
isDoneActivity = map['is_done_activity'],
codeIconActivity = map['code_icon_activity'],
informationActivity = map['information_activity'],
createdDateActivity = map['created_date'];
Map<String, dynamic> toMapForSqflite() {
return {
'id_activity': this.idActivity,
'title_activity': this.titleActivity,
'datetime_activity': this.dateTimeActivity,
'is_done_activity': this.isDoneActivity,
'code_icon_activity': this.codeIconActivity,
'information_activity': this.informationActivity,
'created_date': this.createdDateActivity,
};
}
I want get data where dateTimeActivity is before than date now, then i update isDoneActivity = 1 with this code :
Source code
final passedDateItem = _selectedActivityItem.where((element) {
DateTime convertStringToDateTime =
DateTime.parse(element.dateTimeActivity);
return convertStringToDateTime.isBefore(DateTime.now());
});
if (passedDateItem != null) {
print('Not Null');
} else {
print('Nulledd');
return null;
}
The problem is , passedDateItem return Iterable[ActivityModel] , it's possible to convert it to ActivityModel? So i can easly update like this ?
if (passedDateItem != null) {
passedDateItem.isDoneActivity = 1; <<<
// return passedDateItem.map((e) => e.isDoneActivity = 1);
// final testtt= passedDateItem.
print('Not Null');
} else {
print('Nulledd');
return null;
}
Iterate through passedDateItem
for (var activityModel in passedDateItem) {
//..conditions
activityModel.isDoneActivity = 1;
}
If you are only interested in the first/last element of passedDateItem
use
passedDateItem.first.isDoneActivity == 1
or
passedDateItem.last.isDoneActivity == 1
make sure passedDateItem is not empty in that case.

string contains inside of attribute of list

I wanted to display contact which has id = 'asdf-123' from List of class Contact which have attributes [id, name, phone, dob].
i can do it by doing
bool isContainId = false;
String testId = 'asdf-123';
contacts.foreach((contact) {
if (contact.id == testId) {
isContainId = true;
}
});
however, is there any better way of doing it. something like .contains. please help!.
Contains can not work with custom models in dart, you have to traverse through each object for this kind of operation.
bool isContainId = false;
String testId = 'asdf-123';
isContainId = contacts.firstWhere((contact)=> contact.id == testId, orElse: (){isContainId = false;}) != null;
UPDATE:
class CustomModel {
int id;
CustomModel({this.id});
}
void main() {
List<CustomModel> all = [];
for (var i = 0; i < 4; i++) {
all.add(CustomModel(id: i));
}
bool isContainId = false;
isContainId = all.firstWhere((contact)=> contact.id == 5, orElse: (){isContainId = false;}) != null;
print(isContainId);
}