Reputation: 110
This is the error message I am getting:
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
on the following code:
Product findProductById(String prodId) {
_productsList.firstWhere((element) {
return prodId == element.id;
});
}
I want to find the Product by its id but if its not found what should I return?
Upvotes: 0
Views: 781
Reputation: 399
You can return a empty Product it's not found.
Product findProductById(String productId) {
return productList.firstWhere((element) => element.id == productId,
orElse: () => Product() // make a empty product using default constructor);
}
Upvotes: 1
Reputation: 633
From Dart 2.12 and up, we need to specify whether if a type is nullable or non-nullable. In your case, you should add '?' question mark after the type name Product as you can see below, which will tell the compiler that your function can return a nullable product. Also you forgot to return the filtered product from the productList.
Product? findProductById(String prodId) {
return _productsList.firstWhere((element) {
return prodId == element.id;
});
Upvotes: 1
Reputation: 11486
You're not return
ing inside the findProductById
function:
Product findProductById(String prodId) {
return _productsList.firstWhere((element) {
return prodId == element.id;
});
}
Upvotes: 1