coder0
coder0

Reputation: 75

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.

Upvotes: 4

Views: 9082

Answers (2)

pasanbuddhika
pasanbuddhika

Reputation: 526

Dart does not support non-local returns, so returning from a callback won't break the loop. Dart forEach callback returns void.

You can use any instead of forEach since any callback returns bool. So you can modify your code as follows.

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

    final alreadyInCart = _orders.any((element) {
      if (element.product.id == _lastOrder.product.id) {
       element.colors.add(color);
       element.sizes.add(size);
       element.quantity = element.quantity + quantity;
       notifyListeners();
       return true;
      }
      return false;
    });

    if (alreadyInCart) {
        return;
    }    

    _orders.add(_lastOrder);
    notifyListeners();

  }

Hope this will help you.

Happy coding!

Upvotes: 6

sawin0
sawin0

Reputation: 663

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.

Upvotes: 8

Related Questions