Dart:在foreach循环中从if退出函数

cod*_*er0 3 foreach loops break dart flutter

我想在 if语句,但我无法这样做。

下面是我的代码片段。

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();
  }
Run Code Online (Sandbox Code Playgroud)

谢谢。

小智 7

我认为你应该返回bool或任何其他代替void并使用for代替forEach.

这是您正在寻找的解决方案。

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;
  }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

再会。


pas*_*ika 6

Dart 不支持非本地返回,因此从回调返回不会破坏循环。Dart forEach 回调返回 void。

您可以使用any代替,forEach因为any回调返回 bool。所以你可以按如下方式修改你的代码。

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();

  }
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助。

快乐编码!