Add Up a List With fold
Part of the State Management section of Coddy's Flutter journey. Lesson 8 of 27.
A list of expenses needs a total. You could loop and add, but a list has a method that does exactly this: fold. It walks through the list, carrying one value from item to item:
double total = expenses.fold(0.0, (sum, e) => sum + e.amount);Read it as: start at 0.0. For each expense e, the new sum is the old sum plus e.amount. When the list is done, the last sum is the result. For 3.5 and 12 that is 0.0, then 3.5, then 15.5.
The function must return the new sum. If it returns only e.amount, each step forgets the one before, and the "total" is the last price.
The list itself can change: expenses.add(...) inside setState adds one more, and the next build adds up the new list.
Challenge
EasyThe total line always says $0.00. Work it out instead:
- Set
totalwithexpenses.fold, adding each expense'samount.
The line already shows it with 2 decimals, so it should read Total: $15.50, and grow when you add a snack.
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class Expense {
Expense({required this.name, required this.amount});
final String name;
final double amount;
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final List<Expense> expenses = [
Expense(name: 'Coffee', amount: 3.5),
Expense(name: 'Lunch', amount: 12),
];
@override
Widget build(BuildContext context) {
double total = 0;
return Scaffold(
appBar: AppBar(title: const Text('Expenses')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final e in expenses) Text('${e.name}: \$${e.amount.toStringAsFixed(2)}'),
const SizedBox(height: 16),
Text('Total: \$${total.toStringAsFixed(2)}', style: const TextStyle(fontSize: 28)),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
setState(() {
expenses.add(Expense(name: 'Snack', amount: 2.25));
});
},
child: const Text('Add a snack'),
),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in State Management
2Dart for Models
Methods on Your ClassesGetters in Your ClassesKeep a Field PrivateAdd Up a List With foldPractice on your own: Online Flutter compiler