Errors are thrown by firstwhere method which can be called on Lists
I have a class named Products that holds objects of product(which is model of how each product is) every product object has its own unique id generated using DateTime.now.toString()
Now here I have 2 paths,
**first: ** if I press the update button on my app i will be updating the product already there in my list which i can find using _productList.firstWhere
and it will return me my product without any error
option 2 I add a new product with new id, now i have to check where this id product is already there in my list or not
I am using this logic to check whether the id String is available in my list of products or not
bool hasId(String prod_id) {
late bool result;
_items.firstWhere((element) {
if (element.id == prod_id) {
result = true;
}
if (element.id != prod_id) {
result = false;
}
return result;
});
return result;
}
PROBLEM HERE IS it throws error when it don't find any object with this test
ERROR IS
The following StateError was thrown while handling a gesture:
Bad state: No element
I WANT TO KNOW THAT IT COULDNT FIND ANY OBJECT WITH THAT ID WITHOUT THROWING AN ERROR
NOTE THAT: _ITEMS HOLD OBJECTS WHICH HAVE ID, ALSO I WANT TO RETURN STRING I TRIED, orElse: on firstWhere but it wants an object to be returned which I don't have
CodePudding user response:
It happened because you have some .firstWhere
that never matches and it is never true
You need to use orElse
for the firstWhere
function.
bool hasId(String prod_id) {
bool result = _items.firstWhere((element) => element.id == prod_id, orElse: () => false);
if (result != false) {
return true;
} else {
return false;
}
}
If you have casting issue then you can also do it like this way
bool hasId(String prod_id) {
String result = values.firstWhere((element) => element.id == prod_id, orElse: () => '');
if (result != '') {
return true;
} else {
return false;
}
}
CodePudding user response:
_item.firstWhere() will return your item Model not boolean. So, you may do as the following:
List<Product?> _products = [
Product(id: '123', name: 'P1'),
Product(id: '124', name: 'P2'),
];
bool hasId(String productId) {
bool isExist = false;
Product? product = _products.firstWhere((product) => product?.id == productId, orElse: () => null);
if (product != null) {
isExist = true;
}
return isExist;
}