Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Anonymous Functions


Share

Dart Anonymous Functions

Most functions have a name, like main() or greet().

An anonymous function is a function without a name.

It looks like a normal function, but the return type and the name are left out:

(parameters) {
  // code
}

You often write an anonymous function directly where it is needed, for example as an argument to another function.


Functions Are Values

In Dart, a function is a value, just like a number or a string.

This means you can store a function in a variable, and call it with the variable name:

Example

void main() {
  var greet = (String name) {
    return 'Hello, $name!';
  };

  print(greet('Liam'));
  print(greet('Emma'));
}
Try it Yourself »

Result:

Hello, Liam!
Hello, Emma!

Note the semicolon after the closing curly bracket.

The whole line is a variable declaration, so it ends with ;.

Anonymous functions can also use the arrow syntax:

Example

void main() {
  var square = (int x) => x * x;

  print(square(4));
  print(square(9));
}
Try it Yourself »

Result:

16
81


Passing a Function to forEach()

The most common use of anonymous functions is to pass them to list methods.

The forEach() method calls the function once for every item in the list:

Example

void main() {
  var fruits = ['Apple', 'Banana', 'Cherry'];

  fruits.forEach((fruit) {
    print('I like $fruit');
  });
}
Try it Yourself »

Result:

I like Apple
I like Banana
I like Cherry

The anonymous function (fruit) { ... } gets one item at a time in the parameter fruit.

You do not need to write the type of fruit, because Dart knows that the list contains strings.


map() and where()

The map() method uses a function to change every item, and gives back the new items:

Example

void main() {
  var prices = [10, 20, 30];

  var withTax = prices.map((price) => price * 1.25).toList();
  print(withTax);
}
Try it Yourself »

Result:

[12.5, 25.0, 37.5]

The where() method keeps only the items where the function returns true:

Example

void main() {
  var scores = [45, 82, 67, 91, 30];

  var passed = scores.where((score) => score >= 50).toList();
  print(passed);
}
Try it Yourself »

Result:

[82, 67, 91]

We call toList() because map() and where() do not return a list, but an Iterable, which is a collection you can loop through.


The Function Type

A function can also be a parameter of another function.

The type Function means "any function", but it is better to write the exact type.

The type int Function(int, int) means "a function that takes two int values and returns an int":

Example

int calculate(int a, int b, int Function(int, int) operation) {
  return operation(a, b);
}

void main() {
  print(calculate(6, 3, (x, y) => x + y));
  print(calculate(6, 3, (x, y) => x * y));
}
Try it Yourself »

Result:

9
18

You can also pass a named function, without the parentheses:

Example

int subtract(int a, int b) => a - b;

int calculate(int a, int b, int Function(int, int) operation) {
  return operation(a, b);
}

void main() {
  print(calculate(6, 3, subtract));
}
Try it Yourself »

Result:

3

typedef

A function type can be long and hard to read.

With the typedef keyword, you can give a function type a short name:

Example

typedef Operation = int Function(int, int);

int calculate(int a, int b, Operation operation) {
  return operation(a, b);
}

void main() {
  Operation add = (x, y) => x + y;
  print(calculate(8, 2, add));
  print(calculate(8, 2, (x, y) => x ~/ y));
}
Try it Yourself »

Result:

10
4

Now Operation means the same as int Function(int, int).



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.