Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: Exit a function from if within a foreach loop

I want to break the function after the if statement, but I unable to do so.

Below is my code snippet.

void addOrderToCart(Product product, int quantity, String color, String size) {
    _lastOrder = Order(product, quantity, _orderId++, color, size);

    _orders.forEach((element) {
      if(element.product.id == _lastOrder.product.id){
       element.colors.add(color);
       element.sizes.add(size);
       element.quantity = element.quantity + quantity;
       notifyListeners();
       return;
      }
    });
    _orders.add(_lastOrder);
    notifyListeners();
  }

Thanks.

like image 855
coder0 Avatar asked Nov 06 '25 01:11

coder0


1 Answers

I think you should return bool or any other instead of void and use for instead of forEach.

Here's the solution you looking for.

bool addOrderToCart(Product product, int quantity, String color, String size) {
    _lastOrder = Order(product, quantity, _orderId++, color, size);


    for(var element in _orders){
      if (element.product.id == _lastOrder.product.id) {
        element.colors.add(color);
        element.sizes.add(size);
        element.quantity = element.quantity + quantity;
        notifyListeners();
        return true;
      }
    }
    _orders.add(_lastOrder);
    notifyListeners();
    return true;
  }

Hope this helps.

Good day.

like image 152
sawin0 Avatar answered Nov 07 '25 14:11

sawin0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!