Dart cascades
1 min read

Dart cascades

Using Dart cascades to avoid temporary variables.

Cascades (..) allow for performing a sequence of operations on the same object.

The following code

Cart updateCart(Cart cart, List<Product> products, Discount discount) {
    var updatedCart = cart.adding(products);
    return updatedCart.applying(discount);
}

becomes

Cart updateCart(Cart cart, List<Product> products, Discount discount) {
    return cart.adding(products)
        ..applying(discount);
}

or adding elements to a List

var finalList = someVariable.toList();
finalList.add(anotherObject);
finalList.addAll(anotherListOfObjects);
return finalList

becomes

return someVariable.toList()
    ..add(anotherObject)
    ..addAll(anotherListOfObjects);

At first I found them hard to read. But after using them a couple of times, I got used to them.

Subscribe to a curated newsletter

Receive an email every week with curated content about Dart and Flutter.

See previous issues of the newsletter.