Not properly mapping values in Dart model - flutter

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?,
);
}

Related

Flutter Hive data

I am writing data to a Hive box in flutter using the following data from an API;
{
"deliveryAddresses": [
{
"deliveryAddressNo": "1130119",
"deliveryAddressName": "AIRCRAFT MOVEMENTS 2169 (EAA)",
"pointOfServices": [
{
"deliveryAddressNo": "1130119",
"pointOfServiceNo": "1",
"pointOfServiceName": "HT54505",
"pointOfServiceDescription": ""
},
{
"deliveryAddressNo": "1130119",
"pointOfServiceNo": "2",
"pointOfServiceName": "WASH BAY",
"pointOfServiceDescription": ""
}
]
},
{
"deliveryAddressNo": "1130147",
"deliveryAddressName": "TESCO - 6144 - HARROW APOLLO",
"pointOfServices": [
{
"deliveryAddressNo": "1130147",
"pointOfServiceNo": "1",
"pointOfServiceName": "ACTE711092",
"pointOfServiceDescription": ""
}
]
}
]
}
The data is showing in the Box as i expect however, the 2 pointOfServices for the first account show in the Box as NULL. The 2nd customers pointOfService gets written OK.
Any ideas? Is it because there's 2 sets of data on the first account?
Edited:
Showing my Model code for deliveryAddresses;
List<Order> orderListFromJson(String val) => List<Order>.from(json
.decode(val)['deliveryAddresses']
.map((val) => Order.orderInfofromJson(val)));
#HiveType(typeId: 0)
class Order extends HiveObject {
#HiveField(0)
String? deliveryAddressNo;
#HiveField(1)
String? deliveryAddressName;
#HiveField(2)
List<PointOfServices>? pointOfServices;
Order(
{this.deliveryAddressNo, this.deliveryAddressName, this.pointOfServices});
factory Order.orderInfofromJson(Map<String, dynamic> deliveryAddresses) =>
Order(
deliveryAddressNo: deliveryAddresses['deliveryAddressNo'],
deliveryAddressName: deliveryAddresses['deliveryAddressName'],
pointOfServices: List<PointOfServices>.from(
deliveryAddresses['pointOfServices']
.map((pos) => PointOfServices.fromJson(pos))));
}
Points of service model;
List<PointOfServices> posListFromJson(String val) =>
List<PointOfServices>.from(json
.decode(val)['pointOfServices']
.map((val) => PointOfServices.fromJson(val)));
#HiveType(typeId: 1)
class PointOfServices {
#HiveField(7)
String? deliveryAddressNo;
#HiveField(8)
String? pointOfServiceNo;
#HiveField(9)
String? pointOfServiceName;
#HiveField(10)
String? pointOfServiceDescription;
PointOfServices(
{this.deliveryAddressNo,
this.pointOfServiceNo,
this.pointOfServiceName,
this.pointOfServiceDescription});
factory PointOfServices.fromJson(Map<String, dynamic> pointOfServices) =>
PointOfServices(
deliveryAddressNo: pointOfServices['deliveryAddressNo'],
pointOfServiceNo: pointOfServices['pointOfServiceNo'],
pointOfServiceName: pointOfServices['pointOfServiceName'],
pointOfServiceDescription:
pointOfServices['pointOfServiceDescription']);
}
Code that builds the the data and adds to the box;
if (!Hive.isBoxOpen(orderInfoBox)) {
_orderInfo = await Hive.openBox<Order>('orderInfo_db');
_orderInfo.clear();
var result = await OrderNetwork().get();
var resultBody = await json.decode(json.encode(result.body));
List<Order> orderList = List<Order>.empty(growable: true);
orderList.addAll(orderListFromJson(resultBody));
_orderInfo.addAll(orderList);

How to create a model for pictures from Unsplash?

I need to use the Unsplash API to display a list of pictures that come to me, the title and the author. The problem is that I do not understand how to create a model for converting JSON that comes to me so that I can get the picture, author and title. JSON has nested elements and I don't understand how to do it. How can i do this?
My JSON for one picture:
{
"id":"RBo6ayiFND0",
"created_at":"2022-07-08T13:04:40-04:00",
"updated_at":"2022-07-22T00:20:05-04:00",
"promoted_at":null,
"width":4160,
"height":6240,
"color":"#c0c0c0",
"blur_hash":"LPIOLgtR%1IT~qsSMxxZx]V#s.RP",
"description":null,
"alt_description":null,
"urls":{
"raw":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1",
"full":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?crop=entropy\u0026cs=tinysrgb\u0026fm=jpg\u0026ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1\u0026q=80",
"regular":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?crop=entropy\u0026cs=tinysrgb\u0026fit=max\u0026fm=jpg\u0026ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1\u0026q=80\u0026w=1080",
"small":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?crop=entropy\u0026cs=tinysrgb\u0026fit=max\u0026fm=jpg\u0026ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1\u0026q=80\u0026w=400",
"thumb":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?crop=entropy\u0026cs=tinysrgb\u0026fit=max\u0026fm=jpg\u0026ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1\u0026q=80\u0026w=200",
"small_s3":"https://s3.us-west-2.amazonaws.com/images.unsplash.com/small/photo-1657299156528-2d50a9a6a444"
},
"links":{
"self":"https://api.unsplash.com/photos/RBo6ayiFND0",
"html":"https://unsplash.com/photos/RBo6ayiFND0",
"download":"https://unsplash.com/photos/RBo6ayiFND0/download?ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ",
"download_location":"https://api.unsplash.com/photos/RBo6ayiFND0/download?ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ"
},
"categories":[
],
"likes":21,
"liked_by_user":false,
"current_user_collections":[
],
"sponsorship":{
"impression_urls":[
"https://secure.insightexpressai.com/adServer/adServerESI.aspx?script=false\u0026bannerID=10624831\u0026rnd=[timestamp]\u0026redir=https://secure.insightexpressai.com/adserver/1pixel.gif"
],
"tagline":"Wholesome crispbread from Sweden",
"tagline_url":"https://www.wasa.com/global/",
"sponsor":{
"id":"5tdWPtk6hBg",
"updated_at":"2022-07-22T06:53:49-04:00",
"username":"wasacrispbread",
"name":"Wasa Crispbread",
"first_name":"Wasa Crispbread",
"last_name":null,
"twitter_username":null,
"portfolio_url":"https://www.wasa.com/global/",
"bio":"Things we love:\r\nšŸž Crispbread (naturally) šŸŒ Our planet šŸ˜‹ Delicious food, everyday",
"location":null,
"links":{
"self":"https://api.unsplash.com/users/wasacrispbread",
"html":"https://unsplash.com/#wasacrispbread",
"photos":"https://api.unsplash.com/users/wasacrispbread/photos",
"likes":"https://api.unsplash.com/users/wasacrispbread/likes",
"portfolio":"https://api.unsplash.com/users/wasacrispbread/portfolio",
"following":"https://api.unsplash.com/users/wasacrispbread/following",
"followers":"https://api.unsplash.com/users/wasacrispbread/followers"
},
"profile_image":{
"small":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=32\u0026h=32",
"medium":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=64\u0026h=64",
"large":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=128\u0026h=128"
},
"instagram_username":"wasacrispbread",
"total_collections":0,
"total_likes":0,
"total_photos":73,
"accepted_tos":true,
"for_hire":false,
"social":{
"instagram_username":"wasacrispbread",
"portfolio_url":"https://www.wasa.com/global/",
"twitter_username":null,
"paypal_email":null
}
}
},
"topic_submissions":{
},
"user":{
"id":"5tdWPtk6hBg",
"updated_at":"2022-07-22T06:53:49-04:00",
"username":"wasacrispbread",
"name":"Wasa Crispbread",
"first_name":"Wasa Crispbread",
"last_name":null,
"twitter_username":null,
"portfolio_url":"https://www.wasa.com/global/",
"bio":"Things we love:\r\nšŸž Crispbread (naturally) šŸŒ Our planet šŸ˜‹ Delicious food, everyday",
"location":null,
"links":{
"self":"https://api.unsplash.com/users/wasacrispbread",
"html":"https://unsplash.com/#wasacrispbread",
"photos":"https://api.unsplash.com/users/wasacrispbread/photos",
"likes":"https://api.unsplash.com/users/wasacrispbread/likes",
"portfolio":"https://api.unsplash.com/users/wasacrispbread/portfolio",
"following":"https://api.unsplash.com/users/wasacrispbread/following",
"followers":"https://api.unsplash.com/users/wasacrispbread/followers"
},
"profile_image":{
"small":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=32\u0026h=32",
"medium":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=64\u0026h=64",
"large":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=128\u0026h=128"
},
"instagram_username":"wasacrispbread",
"total_collections":0,
"total_likes":0,
"total_photos":73,
"accepted_tos":true,
"for_hire":false,
"social":{
"instagram_username":"wasacrispbread",
"portfolio_url":"https://www.wasa.com/global/",
"twitter_username":null,
"paypal_email":null
}
}
},
Picture Model:
class PictureModel {
const PictureModel({});
factory PictureModel.fromJson(Map < String, dynamic > json) {
return PictureModel(
...
);
}
}
If I understand correctly you only need:
image
title (I'll assume this is description)
author (I'll assume this is user.name)
You can create the PictureModel as follows:
class PictureModel {
final String author;
final String? title;
final String imageUrl;
const PictureModel({
required this.author,
this.title,
required this.imageUrl,
});
factory PictureModel.fromJson(Map<String, dynamic> json) {
return PictureModel(
author: json['user']['name'],
title: json['description'],
imageUrl: json['urls']['regular'],
);
}
}
Guessing you meant something like below by saying nested.
To simplify it, let's use Photo and Urls properties
class Photo {
Photo({
this.id,
this.urls,
...
});
String? id;
Urls? urls;
...
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json['id'],
urls: Urls.fromJson(json['urls']),
...
);
}
}
Then Urls object.
class Urls {
Urls({
this.rawUrl,
this.fullUrl,
this.regularUrl,
this.smallUrl,
this.thumbUrl,
this.smallS3Url,
});
String? rawUrl;
String? fullUrl;
String? regularUrl;
String? smallUrl;
String? thumbUrl;
String? smallS3Url;
factory Urls.fromJson(Map<String, dynamic> json) => Urls(
rawUrl: json['raw'],
fullUrl: json['full'],
regularUrl: json['regular'],
smallUrl: json['small'],
thumbUrl: json['thumb'],
smallS3Url: json['small_s3'],
);
Map<String, dynamic> toJson() => {
'rawUrl': rawUrl,
'fullUrl': fullUrl,
'regularUrl': regularUrl,
'smallUrl': smallUrl,
'thumbUrl': thumbUrl,
'smallS3Url': smallS3Url,
};
}
Simply you can use any JSON to Dart tool, that takes the JSON and returns a dart model like this one.
Or you can do it manually by making nested classes.
firstly you will make a parent class that contains the first level of the JSON file and each element containing other elements inside will be a separate class and you will use it as a type of the element.
so if we took the first level of the file and one other element from the second level such as the element user your code will be something like this:
class Pic {
Pic.fromJson(dynamic json) {
id = json['id'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
promotedAt = json['promoted_at'];
width = json['width'];
height = json['height'];
color = json['color'];
blurHash = json['blur_hash'];
description = json['description'];
altDescription = json['alt_description'];
urls = Urls.fromJson(json['urls']);
links = Links.fromJson(json['links']);
if (json['categories'] != null) {
categories = [];
json['categories'].forEach((v) {
categories?.add(Categories.fromJson(v));
});
}
likes = json['likes'];
likedByUser = json['liked_by_user'];
if (json['current_user_collections'] != null) {
currentUserCollections = [];
json['current_user_collections'].forEach((v) {
currentUserCollections?.add(CurrentUserCollections.fromJson(v));
});
}
sponsorship = json['sponsorship'] != null ? Sponsorship.fromJson(json['sponsorship']) : null;
topicSubmissions = json['topic_submissions'];
user = User.fromJson(json['user']);
}
String? id;
String? createdAt;
String? updatedAt;
dynamic promotedAt;
int? width;
int? height;
String? color;
String? blurHash;
dynamic description;
dynamic altDescription;
Urls? urls;
Links? links;
List<dynamic>? categories;
int? likes;
bool? likedByUser;
List<dynamic>? currentUserCollections;
Sponsorship? sponsorship;
dynamic topicSubmissions;
User? user;
}
class User {
User.fromJson(dynamic json) {
id = json['id'];
updatedAt = json['updated_at'];
username = json['username'];
name = json['name'];
firstName = json['first_name'];
lastName = json['last_name'];
twitterUsername = json['twitter_username'];
portfolioUrl = json['portfolio_url'];
bio = json['bio'];
location = json['location'];
links = json['links'] != null ? Links.fromJson(json['links']) : null;
profileImage = json['profile_image'] != null ? ProfileImage.fromJson(json['profile_image']) : null;
instagramUsername = json['instagram_username'];
totalCollections = json['total_collections'];
totalLikes = json['total_likes'];
totalPhotos = json['total_photos'];
acceptedTos = json['accepted_tos'];
forHire = json['for_hire'];
social = json['social'] != null ? Social.fromJson(json['social']) : null;
}
String? id;
String? updatedAt;
String? username;
String? name;
String? firstName;
dynamic lastName;
dynamic twitterUsername;
String? portfolioUrl;
String? bio;
dynamic location;
Links? links;
ProfileImage? profileImage;
String? instagramUsername;
int? totalCollections;
int? totalLikes;
int? totalPhotos;
bool? acceptedTos;
bool? forHire;
Social? social;
}
notice that each element that contains other elements inside is with a special data type like Urls Links Sponsorship User in the first class, and Links ProfileImage Social in the second class. so each of these data types is a class on its own but I only mentioned the class User to let you continue the rest of the code.
Happy Coding ;)

Uncorrectly modeling data from Json API response

Trying to fetch data from my API in Flutter. I am able to fetch data from the rest of the fields but not for "Behavior" field.
Here's my json:
[
{
"_id": {
"$oid": "625f2900fe6aeb351381c3f5"
},
"breed": "Africanis",
"origin": "Southern Africa",
"url": "https://en.wikipedia.org/wiki/Africanis",
"img": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4b/Africanis_%281%29.jpg/220px-Africanis_%281%29.jpg",
"WikiDescr": [
{
"contenido": "some content"
}
],
"Behavior": [
{
"good_with_children": 3,
"good_with_other_dogs": 1,
"shedding": 3,
"grooming": 3,
"drooling": 1,
"coat_length": 1,
"good_with_strangers": 2,
"playfulness": 3,
"protectiveness": 5,
"trainability": 3,
"energy": 4,
"barking": 2,
"min_life_expectancy": 10,
"max_life_expectancy": 14,
"max_height_male": 28,
"max_height_female": 28,
"max_weight_male": 130,
"max_weight_female": 100,
"min_height_male": 26,
"min_height_female": 26,
"min_weight_male": 100,
"min_weight_female": 70
}
],
"url_alternative": []
}
]
And here's my dart model generated from https://app.quicktype.io/ :
class DogClass {
Id? _iId;
String? _breed;
String? _origin;
String? _url;
String? _img;
List<WikiDescr>? _wikiDescr;
List<Behavior>? _behavior;
List<dynamic>? _urlAlternative;
DogClass({
Id? iId,
String? breed,
String? origin,
String? url,
String? img,
List<WikiDescr>? wikiDescr,
List<Behavior>? behavior,
List<dynamic>? urlAlternative
}) {
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 (img != null) {
this._img = img;
}
if (wikiDescr != null) {
this._wikiDescr = wikiDescr;
}
if (behavior != null) {
this._behavior = behavior;
}
if (urlAlternative != null) {
this._urlAlternative = urlAlternative;
}
}
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<WikiDescr>? get wikiDescr => _wikiDescr;
set wikiDescr(List<WikiDescr>? wikiDescr) => _wikiDescr = wikiDescr;
List<Behavior>? get behavior => _behavior;
set behavior(List<Behavior>? behavior) => _behavior = behavior;
List<dynamic>? get urlAlternative => _urlAlternative;
set urlAlternative(List<dynamic>? urlAlternative) => _urlAlternative = urlAlternative;
factory DogClass.fromJson(Map<String, dynamic> json) {
return DogClass(
iId: json['_id'] == null
? null
: Id.fromJson(json['_id'] as Map<String, dynamic>),
breed: json['breed'] as String?,
origin: json['origin'] as String?,
url: json['url'] as String?,
img: json['img'] as String?,
wikiDescr: List<WikiDescr>.from(
json["WikiDescr"].map((x) => WikiDescr.fromJson(x))),
behavior: List<Behavior>.from(json["Behavior"].map((x) => Behavior.fromJson(x))),
urlAlternative: List<UrlAlternative>.from(json["url_alternative"].map((x) => UrlAlternative.fromJson(x)))
);
}
}
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 WikiDescr {
WikiDescr({
required this.contenido,
});
String contenido;
factory WikiDescr.fromRawJson(String str) =>
WikiDescr.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory WikiDescr.fromJson(Map<String, dynamic> json) => WikiDescr(
contenido: json["contenido"],
);
Map<String, dynamic> toJson() => {
"contenido": contenido,
};
}
class Behavior {
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;
int? _maxHeightMale;
int? _maxHeightFemale;
int? _maxWeightMale;
int? _maxWeightFemale;
int? _minHeightMale;
int? _minHeightFemale;
int? _minWeightMale;
int? _minWeightFemale;
Behavior(
{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,
int? maxHeightMale,
int? maxHeightFemale,
int? maxWeightMale,
int? maxWeightFemale,
int? minHeightMale,
int? minHeightFemale,
int? minWeightMale,
int? minWeightFemale}) {
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;
}
}
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;
int? get maxHeightMale => _maxHeightMale;
set maxHeightMale(int? maxHeightMale) => _maxHeightMale = maxHeightMale;
int? get maxHeightFemale => _maxHeightFemale;
set maxHeightFemale(int? 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;
factory Behavior.fromJson(Map<String, int> json) =>Behavior(
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']
);
}
class UrlAlternative {
UrlAlternative({
required this.urls,
});
List<String> urls;
factory UrlAlternative.fromJson(Map<String, dynamic> json) => UrlAlternative(
urls: List<String>.from(json["urls"].map((x) => x)),
);
}
Please just focus on "behavior" field. The rest work correctly. Is there something I am missing in my factory method??
I prefer to create my own classes if needed only. I use generators when my data is very complex, your case is not.
You need to firstly deal with raw data then you can use classes and methods because you know how it is structured and how it can be handled to get certain info about it, IMHO.
import 'dart:convert';
import 'package:_samples4/json/json_africa_wiki.dart';
typedef JMap = Map<String, dynamic>;
void main(List<String> args) {
var list = (jsonDecode(rawJsonAfrica) as List).cast<JMap>();
var data = list.first;
var behaviour = (data['Behavior'] as List).first as JMap;
print(behaviour.keys);
print(behaviour.values);
}
Output:
(good_with_children, good_with_other_dogs, shedding, ..., min_weight_male, min_weight_female)
(3, 1, 3, 3, 1, 1, 2, 3, 5, 3, 4, 2, 10, 14, 28, 28, 130, 100, 26, 26, 100, 70)

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 ><

Exception: type 'String' is not a subtype of type 'int' - 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.