# Dart: Calculating the Average of Data in a List

This practical, succinct article walks you through two examples of calculating the average of numerical data in a given list. The first example works with a simple list that contains only numbers, while the second one deals with a list of maps. No more ado; let’s get started.

List of Numbers

To find the result, just use the average getter, like so:

``````// kindacode.com
import 'package:collection/collection.dart';

void main() {
final listOne = [1, 2, 3, 4, 5, 9, 10];
final averageOne = listOne.average;
print(averageOne);

final listTwo = [-3, 1.4, 3.4, 9, 10, 6];
final averageTwo = listTwo.average;
print(averageTwo);
}``````

Output:

``````4.857142857142857
4.466666666666667``````

You don’t even need to calculate the sum of all elements and then divide it by the number of elements. If you want to display the results in a nicer format, see this article: Show a number to two decimal places in Dart (Flutter).

List of Maps

Let’s imagine you have a list of maps where each map contains information about a product, including product name, price, etc. The goal is to find the average price of all products. The program below demonstrates how to solve the problem:

``````// kindacode.com
import 'package:collection/collection.dart';

void main() {
final products = [
{"name": "Product One", "price": 3.33},
{"name": "Product Two", "price": 9.99},
{"name": "Product Three", "price": 5.00}
];

// Create of list of prices
final prices = products.map((product) => product["price"] as double).toList();

// Use the average function to get the average price
final averagePrice = prices.average;
print("Average Price: \$averagePrice");
}``````

Output:

``6.1066666666666665``

You can also tour around our Flutter topic page or Dart topic page for the most recent tutorials and examples.

Subscribe
Notify of
Inline Feedbacks

Related Articles

September 17, 2023

September 17, 2023

September 16, 2023

September 15, 2023

September 15, 2023

September 15, 2023

September 15, 2023

September 14, 2023

September 13, 2023

September 13, 2023

September 11, 2023

September 11, 2023

September 10, 2023

September 1, 2023

August 24, 2023

August 24, 2023

August 19, 2023