With fold
:
final total = cartItems.fold(0, (sum, item) => sum + item.amount);
EDIT: There is a long-running issue with generic methods in Dart that have a callback as a parameter where the type of the arguments cannot be inferred. This wasn't an issue in the past since the default value of a generic argument was dynamic
.
However, with the release of null-safety, the type system of Dart was shaken up, and now the default type is Object?
. This is a problem since you now have to ensure that the objects within the callback aren't nullable before you can add them, and the easiest way to do this is to bypass type inference and explicitly assign a generic type.
There are a few ways you can accomplish this:
// Pass generic type parameters manually
final total = cartItems.fold<int>(0, (sum, item) => sum + item.amount);
// Explicitly type parameters in the callback
final total = cartItems.fold(0, (int sum, item) => sum + item.amount);
// Explicitly type the returned value
final int total = cartItems.fold(0, (sum, item) => sum + item.amount);