How to create a nested function in Dart

In Dart, you can write functions within functions because it is a true object-oriented language. Functions are objects that have type Function.

The inner (nested) function is private to its outer function. Only the outer function can access the inner function by calling it. In Dart, functions form closures, which allow them to be nested. The inner function forms a closure around its variables; therefore, the outer function cannot use the arguments and variables of the inner function. However, since the inner function is within the closure of the outer function, it can access variables and operations from the outer function that have been declared before it.

A closure defines the scope of objects.

In the example below, we nest square in the circleArea function.

svg viewer

Implementation

<html>
<head>
  <script type="application/dart" src="main.dart"></script>
</head>
</html>
How to use a nested function in dart using two syntax versions.

Nest functions in multiple layers

You can have multiple layers of nest functions. In the example below, you can observe two layers of nested functionality. This is also a good example of scope within closures (where c has access to elements of b and a, but the opposite is not true).

<html>
<head>
  <script type="application/dart" src="main.dart"></script>
</head>
</html>
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved