user3048099
user3048099

Reputation: 295

How to search a list of Object by another list of items in 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();

Upvotes: 21

Views: 66120

Answers (5)

Mahadi Hassan
Mahadi Hassan

Reputation: 1016

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-11"},
        {"ags": "01224", "name": "Test-10"},
        {"ags": "22222", "name": "Test-2"},
      ];
    
      bool isDataExist(String value) {
        var data = rows.where((row) => row["name"].contains(value));
        return data.isNotEmpty; // Returns true if at least one match is found
      }
    
      print(isDataExist('Test-1')); //false
      print(isDataExist('Test-11')); //true

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

Upvotes: 28

Jay gajjar
Jay gajjar

Reputation: 151

 var one = [
    {'id': 1, 'name': 'jay'},
    {'id': 2, 'name': 'jay11'},
    {'id': 13, 'name': 'jay222'}
  ];

  int newValue = 13;

  print(one
      .where((oldValue) => newValue.toString() == (oldValue['id'].toString())));

OUTPUT : ({id: 13, name: jay222})

store output in any variable check if variable.isEmpty then new value is unique either

var checkValue = one
      .where((oldValue) => newValue.toString() == (oldValue['id'].toString()))
      .isEmpty;
  if (checkValue) {
    print('Unique');
  } else {
    print('Not Unique');
  }

OUTPUT : Not Unique

Upvotes: 3

Guru Prasad mohapatra
Guru Prasad mohapatra

Reputation: 1969

You can simply use List.where() to filter a list

final List<shop_cart.ShoppingCart> cartprd = snapshot.documents
      .where((f) => shop_cart.ShoppingCart.contains(f.data));

Upvotes: 3

Tom Robinson
Tom Robinson

Reputation: 591

  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.

Upvotes: 31

Sukhi
Sukhi

Reputation: 14135

As of today, you can't.

(A side note : You can use .where, .singleWhere, .firstWhere. This site explains various list/array methods.)

Upvotes: 4

Related Questions