Check whether a list contain an attribute of an object in dart

被刻印的时光 ゝ 提交于 2021-02-18 15:01:48

问题


I need to check whether myItemsList contains myitem.itemId or not, If it exists need to add itemQuantity, if it not exists need to add myitem object to myItemsList.

List<MyItem> myItemsList = new List();

MyItem myitem = new MyItem (
  itemId: id,
  itemName: name,
  itemQuantity: qty,
);

if (myItemsList.contains(myitem.itemId)) {
  print('Allready exists!');
} else {
  print('Added!');
  setState(() {
    myItemsList.add(myitem);
  });
}

MyItem class

class MyItem {
  final String itemId;
  final String itemName;
  int itemQuantity;

  MyItem ({
    this.itemId,
    this.itemName,
    this.itemQuantity,
  });
}

above code is not working as expected, please help me to figure out the issue.


回答1:


You're using contains slightly wrong.

From: https://api.dartlang.org/stable/2.2.0/dart-core/Iterable/contains.html

bool contains(Object element) {
  for (E e in this) {
    if (e == element) return true;
  }
  return false;
}

You can either override the == operator, see: https://dart-lang.github.io/linter/lints/hash_and_equals.html

@override    
bool operator ==(Object other) => other is Better && other.value == value;

Or you can loop over your list and search the normal way one by one, which seems slightly easier.




回答2:


Contains() compares the whole objects.

Besides overriding == operator or looping over, you can use list's singleWhere method:

  if ((myItemsList.singleWhere((it) => it.itemId == myitem.itemId,
          orElse: () => null)) != null) {

Edit: As Dharaneshvar experienced and YoApps mentioned in the comments .singleWhere raises StateError when more elements are found.

This is desired when you expect unique elements such as in the case of comparing IDs.

Raised error is the friend here as it shows that there is something wrong with the data.

For other cases .firstWhere() is the right tool:

  if ((myItemsList.firstWhere((it) => it.itemName == myitem.itemName,
          orElse: () => null)) != null) {

// EO Edit

Whole example:

List<MyItem> myItemsList = new List();
​
class MyItem {
  final String itemId;
  final String itemName;
  int itemQuantity;
​
  MyItem({
    this.itemId,
    this.itemName,
    this.itemQuantity,
  });
}
​
void main() {
  MyItem myitem = new MyItem(
    itemId: "id00",
    itemName: "name",
    itemQuantity: 50,
  );
​
  myItemsList.add(myitem);
​
  String idToCheck = "id00";
​
  if ((myItemsList.singleWhere((it) => it.itemId == idToCheck,
          orElse: () => null)) != null) {
    
    print('Already exists!');
  } else {
    print('Added!');
  }
}


来源:https://stackoverflow.com/questions/55757708/check-whether-a-list-contain-an-attribute-of-an-object-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!