flutter - check if list contains value from another list - flutter

I have two lists, one with posted images and a second with friends.
Only friends posts should be displayed from the posts list.
In this case for Obi.
class postModel{
String? image;
String? userId;
String? name;
int? age;
postModel({this.image, this.userId, this.name, this.age});
}
List<postModel> imageList = [
postModel(image: "imageUrl", userId: "1gw3t2s", name: "Luke", age: 21),
postModel(image: "imageUrl2", userId: "hjerhew", name: "Joda", age: 108),
postModel(image: "imageUrl3", userId: "475fdhr", name: "Obi", age: 30),
postModel(image: "imageUrl4", userId: "jrt54he", name: "Vader", age: 35),];
class friendModel{
String? userId;
String? name;
friendModel({this.userId, this.name});
}
List<friendModel> friendList = [
friendModel(userId: "1gw3t2s", name: "Luke"),
friendModel(userId: "hjerhew", name: "Joda"),];
//...
ListView.builder(
itemCount: imageList.length,
itemBuilder: (context, i) {
return friendList.contains(imageList[i].userId) //something like that
?Image.network(imageList[i].image)
:Container();
}
Output should be only the post from Luke and Joda
thanks

Initialise a new list a and add data to it like below
List<friendModel> a = [];
for(var img in imageList){
for(var frnd in friendList){
if(img.name == frnd.name){
a.add(frnd);
}
}
}
print(a);

If you wanted to avoid double for loops. You could use something like:
for(int i = 0; i < friendList.length; i++) {
var test = imageList.where((e) => e.userId ==
friendList[i].userId).toList();
print(test[0].image);
}
but replace the test var with another list that you can then add to or customize with whatever works for your application.

Related

How to select the desired elements in a list in Dart, and change the data of this element

I have an array with such data (more data in reality)
[
{
serviceid: "979cf8e6",
amount: 1,
price: 0,
materialsPrice: 100,
enable: true,
chenge: true
},
{
serviceid: "979cf812",
amount: 1,
price: 15.5,
materialsPrice: 0,
enable: true,
chenge: false
}
]
My goal is to change "enable" to the desired status in the selected element of the array. For this I will use a block. That is, if when I click on the event, I transfer (false and "979cf8e6") . Then the required element should be found (service = 979cf8e6). And this element should have enable on false. I tried to start something, but it didn't work. Maybe someone knows how to do it?))
on<OnChangeStatusListItemClick>((event, emit) async {
var serviceId = event.serviceId;//(my serviceId here)
var paymentStatus = event.status;//(my new status here)
var paymentDetails = state.listVariant; //(my list here)
PaymentDetailsModel? selected;
paymentDetails = paymentDetails.map((paymentDetailsOne) {
paymentDetailsOne.serviceid == serviceId;
var selectedPaymentDetails = paymentDetailsOne.copyWith(enable: paymentStatus);
return selectedPaymentDetails;
}).toList();
emit(state.copyWith(listVariant: paymentDetails));
});
My PaymentDetailsModel model (this model is used in listVariant)
#freezed
class PaymentDetailsModel with _$PaymentDetailsModel {
#JsonSerializable(fieldRename: FieldRename.none, explicitToJson: true)
const factory PaymentDetailsModel({
required String serviceid,
required double? price,
required int? minmal,
required int amount,
required bool enable,
required bool chenge,
}) = _PaymentDetailsModel;
factory PaymentDetailsModel.fromJson(Map<String, dynamic> json) =>
_$PaymentDetailsModelFromJson(json);
}
I think maybe you miss if else check in your map function, not pretty sure, but you can try :
on<OnChangeStatusListItemClick>((event, emit) async {
final serviceId = event.serviceId;//(my serviceId here)
final paymentStatus = event.status;//(my new status here)
final paymentDetails = state.listVariant.map((paymentDetailsOne) {
if ( paymentDetailsOne.serviceid == serviceId) {
return paymentDetailsOne.copyWith(enable: paymentStatus);
} else {
return paymentDetailsOne;
}
}).toList();
emit(state.copyWith(listVariant: paymentDetails));
});

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

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

Flutter: Transferring items from one list into a different list

i have one List (growable) with an item (actually item 0:
items is of class Team
items[_id = 1, _team = "Team01", _note = "blabla"]
and I want to transfer it into another list with a different structure:
participants is of class User
participants[id = 1, name = "participant1"]
skipping the note and translating _id into id and so on.So at last the result would give me
participants[id = 1, name = "team01"]
(sorry for the writing, I describe it out of the debugger)
i tried something like this, but doesnt work with value:
List<TestTeam> participants;
for (var value in items) {
participants.add(new TestTeam(value.id, value.team));
}
my class Team is defined like this:
class Team {
int _id;
String _team;
String _note;
Team(this._team, this._note);
Team.map(dynamic obj) {
this._id = obj['id'];
this._team = obj['team'];
this._note = obj['note'];
}
int get id => _id;
String get team => _team;
String get note => _note;
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
if (_id != null) {
map['id'] = _id;
}
map['team'] = _team;
map['note'] = _note;
return map;
}
Team.fromMap(Map<String, dynamic> map) {
this._id = map['id'];
this._team = map['team'];
this._note = map['note'];
}
}
You should implement below way
void main() {
List<Team> teams=[];
List<User> participants=[];
for (var i = 0; i < 4; i++) {
teams.add(Team(i,'Team_$i','Note_$i'));
}
for (var value in teams){
participants.add(User(value.id,value.team));
}
for (var value in teams){
print(value.toString());
}
for (var value in participants){
print(value.toString());
}
}
class Team{
int id;
String team;
String note;
Team(this.id,this.team,this.note);
toString()=> 'Team Map :{id:$id,team:$team,note:$note}';
}
class User{
int id;
String team;
User(this.id,this.team);
toString()=> 'User Map :{id:$id,team:$team}';
}
Output
Team Map :{id:0,team:Team_0,note:Note_0}
Team Map :{id:1,team:Team_1,note:Note_1}
Team Map :{id:2,team:Team_2,note:Note_2}
Team Map :{id:3,team:Team_3,note:Note_3}
User Map :{id:0,team:Team_0}
User Map :{id:1,team:Team_1}
User Map :{id:2,team:Team_2}
User Map :{id:3,team:Team_3}