Flutter when serializing list of objects with jsonEncode the final string is getting cutt off - flutter

I have difficulty to convert a long list to JSON string. This is my main model which I want to convert to JSON string
class ActivityBookingRequest {
int adminId;
List<ActivityBookingDetail> activityBookingList;
Map toJson() {
List<Map> activityBookingListMap = this.activityBookingList != null
? this.activityBookingList.map((i) => i.toJson()).toList()
: null;
return {
'adminId': adminId,
'activityBookList': activityBookingListMap,
};
}
}
This is my sub-model which is the list I am trying to serialize!
class ActivityBookingDetail {
int bookingId;
int resourceId;
int sourceId;
String sourceName;
int productId;
String pickupDate;
String cutOffDate;
int adultNumber;
int childrenNumber;
ActivityBookingDetail(
this.bookingId,
this.resourceId,
this.sourceId,
this.sourceName,
this.productId,
this.pickupDate,
this.cutOffDate,
this.adultNumber,
this.childrenNumber,
);
Map<String, dynamic> toJson() {
return {
'ssId': bookingId,
'ssResourceId': resourceId,
'sourceId': sourceId,
'sourceName': sourceName,
'productId': productId,
'pickupDate': pickupDate,
'cutOffDate': cutOffDate,
'noAdult': adultNumber,
'noChild': childrenNumber,
};
}
}
When I convert this to a JSON string if the list is long, the final JSON string is getting cut off!
{"adminId":213,{"ssId":4,"ssResourceId":4,"sourceId":1,"sourceName":"TRES","productId":3,"pickupDate":"2022-09-08T18:30:00","cutOffDate":"2022-09-08T18:30:00","noAdult":1,"noChi

Related

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

Mapping CSV data in flutter

Auto-complete search list
How to parse csv data instead of json data as mentioned in this article. I am new to csv and I have trouble mappping csv data to a model list. I need to pass the csv list to autocomplete field in another package plz help me in mapping it to the model.
class Players {
String keyword;
int id;
String autocompleteterm;
String country;
Players({
this.keyword,
this.id,
this.autocompleteterm,
this.country
});
factory Players.fromJson(Map<String, dynamic> parsedJson) {
return Players(
keyword: parsedJson['keyword'] as String,
id: parsedJson['id'],
autocompleteterm: parsedJson['autocompleteTerm'] as String,
country: parsedJson['country'] as String
);
}
}
class PlayersViewModel {
static List<Players> players;
static Future loadPlayers() async {
try {
players = new List<Players>();
String jsonString = await rootBundle.loadString('assets/players.json');
Map parsedJson = json.decode(jsonString);
var categoryJson = parsedJson['players'] as List;
for (int i = 0; i < categoryJson.length; i++) {
players.add(new Players.fromJson(categoryJson[i]));
}
} catch (e) {
print(e);
}
}

How to compare the type variable in "is" operator in Dart

I couldn't find a way to store the Type value in Map so that I could use it in is operator to check the validity of type using this map later on. Also, can is operator accept Type as a variable?
For eg, Below is hypothetical code solving the problem but it's invalid.
Map<String, Type> map = {
"sku": String,
"price": double,
"quantity": int,
};
dynamic value = 10;
if(value is map["quantity"]){
print("value is of type int and int is expected for quantity value");
}
You can do something like this:
class TypeCheck<T> {
const TypeCheck();
bool typeCheck(dynamic value) => value is T;
}
void main() {
Map<String, TypeCheck> map = {
"sku": TypeCheck<String>(),
"price": TypeCheck<double>(),
"quantity": TypeCheck<int>(),
};
dynamic value = 10;
if (map["quantity"]!.typeCheck(value)) {
print("value is of type int and int is expected for quantity value");
}
}
Im not sure I fully understand I understand what you are trying to do but why don't you try something like.
bool _validate(Map productDetails){
if (productDetails.containsKey("sold_individually") && productDetails["sold_individually"] is bool) {
//return true or false
}
else if (productDetails.containsKey("stock_quantity") && productDetails["stock_quantity"] is int){
//return true or false
}
else if (productDetails.containsKey("tax_class") && productDetails["tax_class"] is String && productDetails["tax_class"].isNotEmpty) {
//return true or false
} else {
//return true or false
}
}
As for the other part of your question you wont get an error but you will always return false. In contrast if you check if a variable is dynamic it will always return true.
I don't really understand your end goal. But from what you have, I don't think you are taking advantage of the strongly-typed nature of dart.
Assuming you are getting your map from an API, you could enforce
typing manually in your code as follows;
Map<String, Type> map = {
"sku": json['key'] as String,
"price": json['key'] as double,
"quantity": json['key'] as int,
};
And avoid using dynamic when declaring variables.
OR
In the case you have a user-defined type you what to compare, you can use the equatable package on a class for instance as follows;
class CustomMap extends Equatable {
String sky;
double price;
int quantity;
// here you put the fields of a class you want for two instances of a class to be equal.
#overide
List<Object> get props => [sky, price, quantity];
}
Update from your comment
You should have a custom class for the API objects for instance;
class Item extends Equatable {
String sku;
double price;
int quantity;
Item({this.sky, this.price, this.quantity});
// factory constructor
factory Item.fromMap(Map<String, dynmic> json) {
final sku = json['sku'] as String,
final price = (json['price'] as num) as double,
final quantity = json['quantity'] as num,
return Item(sku: sku, price: price, quantity: quantity);
}
// define equatable objects
#override
List<Object> get props => [sku, price, quantity];
}
Now you can use it as follows;
Future<Item> objectsFromService(Map<String, dynamic> json ) async {
http.Response response = http.get(url);
if(response.status == 200) {
final decodedJson = json.decode(response.body);
return Item.fromJson(decodedJson);
}else{
print('Error fetch data');
return null;
}
}
Hope it helps

How to check if a class contains null in Flutter

I have a class
class Job {
String id;
String jobTitle;
String updatedAt;
String createdAt;
Job(
{this.id,
this.jobTitle,
this.updatedAt,
this.createdAt});
factory Job.fromMap(Map data) {
return Job(
id: data['id'],
jobTitle: data['jobTitle'],
updatedAt: data['updatedAt'],
createdAt: data['createdAt'],
);
}
}
After assigning values:
Job _job = new Job();
For instance _job.jobTitle = 'farmer';
Before saving to the backend, I want to make sure there are no null values within, the _job object.
Rather than checking for each item in the object class e.g
If(_job.jobTitle != null && _job.updatedAt != null && ....){
}
How can I do a one-step check if the object class contains any null values?
Something like
if(_job.contains(null)){
}
You can create another method to check if any of fields is null:
class Job {
String id;
String jobTitle;
String updatedAt;
String createdAt;
Job({this.id, this.jobTitle, this.updatedAt, this.createdAt});
factory Job.fromMap(Map data) {
return Job(
id: data['id'],
jobTitle: data['jobTitle'],
updatedAt: data['updatedAt'],
createdAt: data['createdAt'],
);
}
bool checkIfAnyIsNull() {
return [id, jobTitle, updatedAt, createdAt].contains(null);
}
}
void main() {
Job _job = Job();
// Comment any of these fields and you would get [true].
// [false] means all fields are set.
_job.id = "1";
_job.jobTitle = "Developer";
_job.createdAt = "27-11-2019";
_job.updatedAt = "28-11-2019";
if(_job.checkIfAnyIsNull()){
print("Not all fields are set");
}
}
the Best Approach is to assign a null to the Object
_job = null ;
and then add the new Details

How to insert a List<Class> into a Map<String, dynamic> in dart?

My problem is that I have a list of the following class:
class ingreso_Egreso_Dummy{
int tipo;
String monto;
String moneda;
String descripcion;
}
then I want to insert the data into a Map which later will be converted into a json and which I am creating like this:
Map<String, dynamic> body;
body = {
"Cod_Prom": "01",
"CodCli": "003526",
"Status": _index_status.toString(),
"NOMBRE": controller_nombre.text,
"APELLIDOS": controller_apellidos.text,
"solicitud":[{
"Cod_Solicit": 1.toString(),
"Fecha": DateFormat("y-d-M").format(DateTime.now()),
"Status_Solicit": "E",}],
"prestamo":[{
"Monto_Solicit":controller_monto_solic.text,
"Plazo":controller_plazo.text,
"Cod_TipoPlazo":_index_tipoplazo.toString(),
"Nombre_Resp":controller_nombreresp.text,
"Telf_Resp":controller_telefonoresp.text,}],
"Ingresos": [{
//// here I want create a loop that returns a map for each value
//// of the list like this:
//// "Descripcion": Listaingresos[i].descripcion;
})
}]
};
Every help is very appreciated, thank you.
// camelCaseStyle is a standard for class names for Dart
class IngresoEgresoDummy {
int tipo;
String monto;
String moneda;
String descripcion;
Map<String, dynamic> toJson(){
return {
'tipo': tipo,
'monto': monto,
'monedo': moneda,
'descripcion': descripcion
};
}
}
and after that
List<IngresoEgresoDummy> listaingresos= List();
Map<String, dynamic> body = {
// all your params
"Ingresos": listaingresos.map((ingreso) => ingreso.toJson()).toList()
// all your params
};