Home > Software design >  flutter - check if list contains value from another list
flutter - check if list contains value from another list

Time:05-07

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

CodePudding user response:

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

CodePudding user response:

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