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 Closures


Share

Dart Closures

A function can use variables that are defined outside of it.

A closure is a function that remembers these outside variables, even when it is called later, in another place.

In this example, the anonymous function uses the variable greeting from main():

Example

void main() {
  var greeting = 'Hello';

  var greet = (String name) => '$greeting, $name!';

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

Result:

Hello, Liam!

The function greet is a closure, because it uses greeting, which is not one of its parameters.


A Counter Example

Closures become really useful when a function returns another function.

The function makeCounter() creates a variable count and returns a function that adds 1 to it:

Example

int Function() makeCounter() {
  var count = 0;
  return () {
    count++;
    return count;
  };
}

void main() {
  var counter = makeCounter();

  print(counter());
  print(counter());
  print(counter());
}
Try it Yourself »

Result:

1
2
3

Example Explained

  • The return type int Function() means that makeCounter() returns a function that takes no parameters and returns an int.
  • When makeCounter() is finished, its local variable count would normally be gone.
  • But the returned function still uses count, so Dart keeps it alive.
  • Each call to counter() changes the same count, so the result goes up by 1 every time.


Each Closure Has Its Own Variables

Every call to makeCounter() creates a new count variable.

So two counters do not share their values:

Example

int Function() makeCounter() {
  var count = 0;
  return () {
    count++;
    return count;
  };
}

void main() {
  var applesCounter = makeCounter();
  var orangesCounter = makeCounter();

  print(applesCounter());
  print(applesCounter());
  print(orangesCounter());
}
Try it Yourself »

Result:

1
2
1

Closures With Parameters

A closure can also remember a parameter of the outer function.

Here, makeMultiplier() returns a function that multiplies a number by factor:

Example

int Function(int) makeMultiplier(int factor) {
  return (int x) => x * factor;
}

void main() {
  var timesTwo = makeMultiplier(2);
  var timesThree = makeMultiplier(3);

  print(timesTwo(5));
  print(timesThree(5));
}
Try it Yourself »

Result:

10
15

The function in timesTwo remembers that factor is 2, and the function in timesThree remembers that factor is 3.


Closures See the Current Value

A closure does not copy the value of a variable.

It uses the variable itself, so it always sees the current value:

Example

void main() {
  var name = 'Emma';
  var greet = () => print('Hello, $name');

  greet();
  name = 'Noah';
  greet();
}
Try it Yourself »

Result:

Hello, Emma
Hello, Noah

Remember: A closure is just a function that uses variables from the place where it was created.

You use closures every time you pass an anonymous function to methods like forEach() or where() and use a variable from outside it.



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.