'flutter - check if list contains value from another list
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
Solution 1:[1]
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);
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alind Sharma |
Solution 2 | Tray Denney |