Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
programming
function

How to create a nested function in Dart

Educative Answers Team

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>

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>

RELATED TAGS

dart
programming
function
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring