Built-in way to get sum and average of list items in dart
tmaihoff opened this issue · comments
You use the reduce
method to get the sum of list items in dart. Calculating the Sum of List Items in Dart
Actually there is a built-in way for doing that:
import 'package:collection/collection.dart';
void main() {
final list = [1, 2, 3, 4];
final sum = list.sum;
print(sum); // prints 10
final average = list.average;
print(average); // prints 2.5
}
@tmaihoff I'm aware of that some of the tips and tricks which I put out, have already convenience functions or classes available elsewhere. Nonetheless I find it personally to be useful to know how things are done under the hood and I know a lot of programmers are also curious about this.
Like always, there is a fine line between reinventing the wheel and just reusing what's already there but the goal of this repo is to provide interesting solutions to every day problems and since sometimes doing the code ourselves is the most fun and a bigger challenge, I choose to provide a custom solution sometimes rather than using a package or a dependency.
Thanks for your detailed answer, completely understand your point 👍
Thank you too @tmaihoff 👍