Using value/variable used in if.clause after the if - flutter

I want to create a new address model. Doing so, beforehand I check a data structure if this contains specific information and then extract them and store it into a variable. After all if-clauses I want to use these variables to create a new object of type Address. However, all the in-between stored variables are not recognized:
final List type = c['types'];
if (type.contains('street_number')) {
final streetNumber = c['long_name'];
}
if (type.contains('route')) {
final street = c['long_name'];
}
if (type.contains('locality')) {
final city = c['long_name'];
}
if (type.contains('postal_code')) {
final zipCode = c['long_name'];
}
final address = Address(
country: null,
postalCode: zipCode, //Undefinex name 'zipCode'
city: city,
streetNumber: streetNumber,
long: null,
lat: null);
});

Variables which are declared in a code block will be removed after that block. So you have to declare that Variables before those blocks:
dynamic streetNumber;
if (type.contains('street_number')) {
streetNumber = c['long_name'];
}
dynamic street;
if (type.contains('route')) {
street = c['long_name'];
}
dynamic city;
if (type.contains('locality')) {
city = c['long_name'];
}
dynamic zipCode;
if (type.contains('postal_code')) {
zipCode = c['long_name'];
}

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

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]' for Flutter

I am trying to store my database value into a class, but i was unable to convert it into my class using DataSnapshot. I have already added all necessary null safety operators. But it still shows an error.
class User {
String userID = "";
String name = "";
String phoneNo = "";
String email = "";
String password = "";
User(
{required this.userID,
required this.name,
required this.phoneNo,
required this.email,
required this.password});
User.fromSnapshot(DataSnapshot dataSnapshot) {
userID = dataSnapshot.key!;
if (dataSnapshot.value != null) {
name = dataSnapshot.value!["name"] as String;
email = dataSnapshot.value!['email'];
phoneNo = dataSnapshot.value!['phone'];
password = dataSnapshot.value!['password'];
}
}
}
I am trying to define the snapshot value as a String but also the same as others.
Error message
try
if (dataSnapshot.value != null) {
final data = dataSnapshot.value as Map;
name = data["name"] as String;
email = data['email'] as String;
phoneNo = data['phone'] as String;
password = data['password'] as String;
}
Try to specify the type of your DataSnapshot:
User.fromSnapshot(DataSnapshot<Map<String,dynamic>> dataSnapshot) {
userID = dataSnapshot.key!;
if (dataSnapshot.value != null) {
name = dataSnapshot.value!["name"] as String;
email = dataSnapshot.value!['email'];
phoneNo = dataSnapshot.value!['phone'];
password = dataSnapshot.value!['password'];
}
}

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

Flutter object coping and updating issue

I Have model
class Address {
String firstName;
String lastName;
//1 for shipping and 2 for billing address
int addressType=1;
String middleName;
String company;
String email;
String phone;
String country;
String city;
String state;
String zip;
String address;
Address({this.firstName,this.addressType, this.lastName, this.middleName, this.company, this.email, this.phone, this.country, this.city, this.state, this.zip, this.address});
Address.fromJson(Map<dynamic, dynamic> json) {
firstName = json['firstName'];
lastName = json['lastName'];
middleName = json['middleName'];
company = json['company'];
email = json['email'];
phone = json['phone'];
country = json['country'];
addressType=json['addressType'];
city = json['city'];
state = json['state'];
zip = json['zip'];
address = json['address'];
}
Map<dynamic, dynamic> toJson() {
final Map<dynamic, dynamic> data = new Map<dynamic, dynamic>();
data['firstName'] = this.firstName;
data['lastName'] = this.lastName;
data['addressType']=this.addressType;
data['middleName'] = this.middleName;
data['company'] = this.company;
data['email'] = this.email;
data['phone'] = this.phone;
data['country'] = this.country;
data['city'] = this.city;
data['state'] = this.state;
data['zip'] = this.zip;
data['address'] = this.address;
return data;
}
}
and I created 3 objects
Address obj1,obj2,obj3;
and i added value in obj1 and obj1.addressType=1; then I copied it two obj2 and obj3 like obj2=obj1; obj2.addressType=1; and obj3=obj1;
then I updated obj1 value obj1.addressType=2;
But when I added this 3 object to db it saved as obj1 with new updates
which means addressType is 2 for all objects Why this is happening?
In Flutter it will not create new objects it will refer the same objects in memory, so if you want to copy that object then you can follow the below way.
Add this in your address class.
Address.clone(Address address)
: this(
addressType: address.addressType,
// add all properties like this here
);
How You can use. it.
a1.addressType = 1;
a2 = Address.clone(a1);
a2.addressType = 2;
print(a1.addressType); // it will print 1

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