Fold Method In Dart and Flutter

In these articles, we will discuss the fold method that are used in the dart and flutter. What shall we do today is add two textfield to the screen and add one Button to show their output result as a sum in the table by using a fold method.

The Fold method Reduces a collection to a single value by iteratively combining each element of the collection with an existing value using the provided function. The fold can be used in all cases. They are used to generate a single value by combining the elements of the list. The fold method for a List takes two arguments; the start value and a function. This function also takes two arguments; the accumulated value and the current item in the list.

Let’s take a basic example of the fold method.

Example 1: Calculating the sum of a list

void main() {
 
// find all the sum of given number in the list

  List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  int sum = numbers.fold(0, (a, b) => a + b);
  print(sum);
}

The output of the above code will be 55.

Example 2: To calculate the total age of the Class Person

void main() {
  
final names =
      name.fold<int>(0, (previousValue, value) => previousValue + value.age);

  print('$names');

}

class Person {
  final String name;
  final int age;

  Person(this.name, this.age);
}

List<Person> name = [
  Person('A', 10),
  Person('B', 20),
  Person('C', 30),
  Person('D', 40),
  Person('E', 50),
  Person('F', 60),
];

The output of the above code will be 210

Example 3: To find the largest number in the given list

void main() {
  final myList = [1, 3, 5, 8, 7, 2, 11];
  final result = myList.fold(myList.first, (max, element){
    if(max < element) max = element; 
    return max; 
  });
  
  print(result);
}

The output of the above code will be 11.

Example 4: Find the Smallest number in the given list

oid main() {
  final myList = [10, 3, 5, 8, 7, 2, 11];
  final result = myList.fold(myList.first, (min, element){
    if(min > element) min = element; 
    return min; 
  });
  
  print(result);
}

The output of the above code will be 2

Now let’s take another example of how we can implement with the help of flutter:

import 'package:flutter/material.dart';


class FoldScreen extends StatefulWidget {
  const FoldScreen({Key? key}) : super(key: key);

  @override
  State<FoldScreen> createState() => _FoldScreenState();
}

class _FoldScreenState extends State<FoldScreen> {
  final _formKey = GlobalKey<FormState>();
  final itemcontroller = TextEditingController();
  final pricecontroller = TextEditingController();
  List<Item> item = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Fold Method'),
          centerTitle: true,
        ),
        body: Container(
          padding: const EdgeInsets.all(8.0),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                TextField(
                    controller: itemcontroller,
                    decoration: InputDecoration(
                        hintText: 'Items',
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(
                            10,
                          ),
                        ))),
                const SizedBox(
                  height: 10,
                ),
                TextField(
                    keyboardType: TextInputType.number,
                    controller: pricecontroller,
                    decoration: InputDecoration(
                        hintText: 'Price',
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(
                            10,
                          ),
                        ))),
                Container(
                  padding: const EdgeInsets.all(8),
                  width: double.infinity,
                  child: ElevatedButton(
                      onPressed: () {
                        if (_formKey.currentState!.validate()) {
                          item.add(Item(itemcontroller.text,
                              int.parse(pricecontroller.text)));

                          setState(() {
                            itemcontroller.clear();
                            pricecontroller.clear();
                          });
                        }
                      },
                      child: const Text('Submit')),
                ),
                const SizedBox(
                  height: 20,
                ),
                Container(
                  padding: const EdgeInsets.all(8),
                  width: double.infinity,
                  child: DataTable(
                      dataRowColor: MaterialStateProperty.resolveWith<Color?>(
                          (Set<MaterialState> states) {
                        Colors.red;
                        return null; // Use the default value.
                      }),
                      sortAscending: true,
                      border:
                          TableBorder(borderRadius: BorderRadius.circular(10)),
                      columns: const [
                        DataColumn(label: Text('Item')),
                        DataColumn(label: Text('Price'))
                      ],
                      rows: [
                        ...item.map((e) => DataRow(cells: [
                              DataCell(Text(e.item)),
                              DataCell(Text(e.price.toString())),
                            ])),
                        DataRow(
                            color: MaterialStateColor.resolveWith(
                                (Set<MaterialState> states) =>
                                    states.contains(MaterialState.selected)
                                        ? Colors.red
                                        : Colors.white),
                            cells: [
                              const DataCell(Text(
                                'Total amount',
                                style: TextStyle(fontWeight: FontWeight.bold),
                              )),
                              DataCell(Text(
                                item
                                    .fold<int>(0, (a, b) => a + b.price)
                                    .toString(),
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold),
                              )),
                            ]),
                      ]),
                )
              ],
            ),
          ),
        ));
  }
}

class Item {
  final String item;
  final int price;
  Item(this.item, this.price);
}

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

Thank you for reading the guide on the Fold method in dart and flutter.

Related: Slivers And CustomScrollView In Flutter