Anonymous Functions
Part of the Logic & Flow section of Coddy's Dart journey — lesson 44 of 65.
So far, you've been creating functions with names like calculateTotal or printMessage. But sometimes you need a simple function for just one specific task, and giving it a name feels unnecessary. This is where anonymous functions come in handy.
An anonymous function is a function without a name. You define it right where you need it, making your code more concise for short, one-time operations. The syntax is straightforward - you simply write the parameter list followed by the function body:
(parameter) {
// function body
}Anonymous functions are particularly useful with list methods. For example, instead of creating a separate named function to print each item in a list, you can use an anonymous function directly with the forEach method:
List<String> fruits = ['apple', 'banana', 'orange'];
fruits.forEach((fruit) {
print(fruit);
});This approach keeps your code clean and focused, especially when the function logic is simple and won't be reused elsewhere in your program.
Challenge
EasyCreate a program that processes a list of employee names using anonymous functions. Your program will demonstrate how to use anonymous functions with the forEach method to perform different operations on each list element.
- Read a string input containing employee names separated by commas (e.g.,
"Alice,Bob,Charlie,Diana") - Split the input string into a list of individual names using the
split()method - Use the
forEachmethod with an anonymous function to print each employee name with a welcome message - Use the
forEachmethod with another anonymous function to print each employee name in uppercase - Use the
forEachmethod with a third anonymous function to print each employee name along with its character count
For example, if the input is "Alice,Bob,Charlie", your program should output:
Processing employee list: Alice,Bob,Charlie
===========================================
Welcome Messages:
Welcome to the team, Alice!
Welcome to the team, Bob!
Welcome to the team, Charlie!
===========================================
Names in Uppercase:
ALICE
BOB
CHARLIE
===========================================
Name Lengths:
Alice has 5 characters
Bob has 3 characters
Charlie has 7 charactersIf the input is "John,Sarah", your program should output:
Processing employee list: John,Sarah
===========================================
Welcome Messages:
Welcome to the team, John!
Welcome to the team, Sarah!
===========================================
Names in Uppercase:
JOHN
SARAH
===========================================
Name Lengths:
John has 4 characters
Sarah has 5 charactersYour program must use three separate forEach method calls, each with its own anonymous function. The anonymous functions should be defined inline without giving them names. Each anonymous function should take a single parameter representing the current employee name and perform the specified operation. Use string interpolation to format the output messages exactly as shown above.
Cheat sheet
An anonymous function is a function without a name, defined right where you need it. The syntax uses parameter list followed by the function body:
(parameter) {
// function body
}Anonymous functions are particularly useful with list methods like forEach:
List<String> fruits = ['apple', 'banana', 'orange'];
fruits.forEach((fruit) {
print(fruit);
});This approach keeps code clean and focused for simple, one-time operations that won't be reused elsewhere.
Try it yourself
import 'dart:io';
void main() {
// Read the input string containing employee names
String? input = stdin.readLineSync();
// Split the input into a list of names
List<String> employeeNames = input!.split(',');
// Print the initial processing message
print('Processing employee list: $input');
print('===========================================');
// TODO: Write your code below
// Use forEach with anonymous functions to:
// 1. Print welcome messages
// 2. Print names in uppercase
// 3. Print name lengths
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List