Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a list of Object by another list of items in dart

Tags:

flutter

dart

How to search a list of a class object with one of its property matching to any value in another list of strings

I am able to get filtering based on a single string , but not on a list of strings

final List<shop_cart.ShoppingCart> cartprd = snapshot.documents
      .map((f) => shop_cart.ShoppingCart.fromMap(f.data))
      .toList();
like image 616
user3048099 Avatar asked Jul 04 '19 08:07

user3048099


Video Answer


2 Answers

In case if you want to check for a value in a list of objects . you can follow this :

 List rows = [
          {"ags": "01224", "name": "Test-1"},
          {"ags": "01224", "name": "Test-1"},
          {"ags": "22222", "name": "Test-2"},
        ];
    
    bool isDataExist(String value) {
    var data= rows.where((row) => (row["name"].contains(value)));
      if(data.length >=1)
     {
        return true;
     }
    else 
     {
        return false;
     }
    }   

you can put your own array of objects on rows . replace your key with name . you can do your work based on true or false which is returned from the function isDataExist

like image 134
Mahadi Hassan Avatar answered Sep 21 '22 09:09

Mahadi Hassan


  List<SomeClass> list = list to search;
  List<String> matchingList = list of strings that you want to match against;

  list.where((item) => matchingList.contains(item.relevantProperty));

If the number of items in list is large, you might want to do:

  List<SomeClass> list = list to search;
  List<String> matchingList = list of strings that you want to match against;

  final matchingSet = HashSet.from(matchingList);

  list.where((item) => matchingSet.contains(item.relevantProperty));

Or else just always store the matching values as a hashset.

like image 26
Tom Robinson Avatar answered Sep 22 '22 09:09

Tom Robinson