How to create a model for pictures from Unsplash? - flutter

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

Related

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

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

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

Need help to get specific <key,Value> pair depeding upon a sinlge value from values in a Map

I am trying to get <key,Value> pairs thorugh a single value from values of map.
I am trying to display all the books that have status = true.
But i don't know how can i access status from librarian class(as status is member variable of Book class) and how i can get to the column of status as there are many value for each key.
BOOK CLASS
class Book {
String BookID = '';
String Author ='';
String Name='';
int RackNo=0;
int Price = 0;
bool status = true;
int Edition = 0;
String DateOfPurchase='';
static var count=0;
static var BookList = <String,Object>{};
Book(String BookID , String Author,String Name, int RackNo,int Price, bool status,int Edition,String DateOfPurchase){
this.BookID=BookID;
this.Author=Author;
this.Name=Name;
this.RackNo=RackNo;
this.Price=Price;
this.status=status;
this.Edition=Edition;
this.DateOfPurchase=DateOfPurchase;
BookList[this.BookID]={this.Name, this.Author,this.Name,this.RackNo,this.Price,this.status,this.Edition,this.DateOfPurchase};
count++;
}
void DisplayBookDetails(String ID){
print(BookList[ID]);
}
void UpDateStatus(bool newStatus){
status=newStatus;
}
}
Librarian Class
import 'package:untitled2/Book.dart';
class Librarian {
int count=0;
String Name = '';
String Password = '';
Librarian(String Name,String Password){
this.Name = Name;
this.Password=Password;
}
void SearchBook(String ID){
print(Book.BookList[ID]);
}
void ShowAvailableBooks() {
Book.BookList.values.forEach((element) {print(element);});
}
}
what i am trying to achieve is something like this
if(Book.BookList.values.status==true)//all the books tha have status == true
{
print(Book.BookList[ID's of those books])//display all those books
}
Sorry in advance for poor Question Composition as it is my first time asking a question
Here is an example. I changed your classes around because they were constructed weirdly and you had bookList as a static variable within Book, which wouldn't really work. The main functionality you asked for is in the showAvailableBooks function.
class Book {
final String id;
final String title;
final String? author;
final int? rackNo;
final int? price;
final int? edition;
final String? dateOfPurchase;
bool status;
Book({
required this.id,
required this.title,
this.author,
this.rackNo,
this.price,
this.edition,
this.dateOfPurchase,
this.status = false,
});
void set setStatus(bool newStatus) {
status = newStatus;
}
void printBook() {
print('id: $id, title: $title, author: $author');
}
}
class Librarian {
final String name;
final String password;
Map<String, Book> books = {};
int count = 0;
Librarian({required this.name, required this.password});
void addBooks(List<Book> bookList) {
for (Book book in bookList) {
books[book.id] = book;
count += 1;
}
}
void displayBookDetails(String id) {
books[id]?.printBook();
}
//The function you want
void showAvailableBooks() {
List<String> available = books.keys.where((id) => books[id]!.status == true).toList();
for (String bookID in available) {
books[bookID]?.printBook();
}
}
}
void main() {
Librarian librarian = Librarian(
name: "Mrs. Librarian",
password: "Password123",
);
//Unavailable - status: false
Book book1 = Book(
id: 'abc-123',
title: 'Book 1',
author: 'Author One',
);
//Available - status: true
Book book2 = Book(
id: 'def-456',
title: 'Book 2',
author: 'Author Two',
status: true
);
//Available - status: true
Book book3 = Book(
id: 'ghi-789',
title: 'Book 3',
author: 'Author Three',
status: true
);
librarian.addBooks([book1, book2, book3]);
/*The function you want - prints only books with status: true*/
print('Before changing book1 status to true');
librarian.showAvailableBooks();
book1.setStatus = true;
print('\nAfter changing book1 status to true');
librarian.showAvailableBooks();
}

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