Dart: Exit a function from if within a foreach loop

4,070

Solution 1

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.

Solution 2

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!

Share:
4,070
Admin
Author by

Admin

Updated on December 20, 2022

Comments

  • Admin
    Admin over 1 year

    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.