Recursion
suggest changeA recursive function is a function that calls itself. Each call solves a smaller version of the problem, until the problem is small enough to answer directly.
Every correct recursive function has two parts:
- a base case that returns without recursing, and
- a recursive case that makes progress toward the base case.
Recursion is the natural fit for data that is itself recursive: trees, nested lists and maps, JSON documents, directory hierarchies, expression trees. It is also a clean way to express divide-and-conquer and backtracking algorithms.
Dart has no special syntax for recursion; any function, method, local function or getter can call itself. What you do need to know is that Dart does not perform tail call optimization, so every call uses a stack frame and very deep recursion throws StackOverflowError. This article covers both the useful patterns and how to stay out of that trap.
A first example: factorial
n! is n * (n - 1)!, and 1! is 1. That definition translates directly into code:
int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
BigInt bigFactorial(int n) =>
n <= 1 ? BigInt.one : BigInt.from(n) * bigFactorial(n - 1);
void main() {
print(factorial(5));
print(factorial(20));
print(factorial(21)); // overflows 64-bit int
print(bigFactorial(30));
}
Output:
120
2432902008176640000
-4249290049419214848
265252859812191058636308480000000
factorial(21) silently overflows because a native int is 64 bits (when compiled to JavaScript it would lose precision instead). BigInt has no such limit, and the recursive structure is identical.
Forgetting the base case, or writing a recursive case that doesn't move toward it (for example factorial(n) instead of factorial(n - 1)), produces infinite recursion that ends in a stack overflow.
Recursion over lists and strings
A list is either empty or a first element followed by the rest of the list. Dart 3 Pattern matching lets you write exactly that with a switch expression and a rest pattern:
int sum(List<int> xs) => switch (xs) {
[] => 0,
[final first, ...final rest] => first + sum(rest),
};
int sumFrom(List<int> xs, [int i = 0]) =>
i == xs.length ? 0 : xs[i] + sumFrom(xs, i + 1);
String reverse(String s) =>
s.isEmpty ? '' : reverse(s.substring(1)) + s[0];
bool isPalindrome(String s) {
if (s.length < 2) return true;
if (s[0] != s[s.length - 1]) return false;
return isPalindrome(s.substring(1, s.length - 1));
}
void main() {
print(sum([1, 2, 3, 4, 5]));
print(sumFrom([1, 2, 3, 4, 5]));
print(reverse('recursion'));
print(isPalindrome('racecar'));
print(isPalindrome('dart'));
}
Output:
15
15
noisrucer
true
false
The switch in sum is exhaustive: the analyzer knows that [] and [first, ...rest] together cover every list.
The pattern version is elegant, but ...rest copies the remaining elements on every call, which makes it O(n²). sumFrom passes an index instead and copies nothing. Use an index (or a loop) for large inputs; the same applies to substring in reverse and isPalindrome.
Walking nested data
Data decoded from JSON is a tree of List, Map and scalar values, and you rarely know how deep it goes. A recursive function handles any depth in a few lines. Type patterns in a switch pick the right case for each node:
int sumDeep(Object? value) => switch (value) {
int n => n,
List<Object?> items => items.fold(0, (acc, e) => acc + sumDeep(e)),
Map<String, Object?> m => m.values.fold(0, (acc, e) => acc + sumDeep(e)),
_ => 0,
};
List<Object?> flatten(List<Object?> items) => [
for (final item in items)
if (item is List<Object?>) ...flatten(item) else item,
];
void printTree(Map<String, Object?> node, [String indent = '']) {
for (final MapEntry(:key, :value) in node.entries) {
if (value is Map<String, Object?>) {
print('$indent$key/');
printTree(value, '$indent ');
} else {
print('$indent$key ($value bytes)');
}
}
}
void main() {
final data = [
1,
[2, 3, [4, 5]],
{'a': 6, 'b': [7, 'x']},
];
print(sumDeep(data));
print(flatten([1, [2, [3, [4]], 5], 6]));
printTree({
'src': {
'main.dart': 1200,
'util': {'math.dart': 300, 'strings.dart': 450},
},
'pubspec.yaml': 210,
});
}
Output:
28
[1, 2, 3, 4, 5, 6]
src/
main.dart (1200 bytes)
util/
math.dart (300 bytes)
strings.dart (450 bytes)
pubspec.yaml (210 bytes)
flatten shows that recursion works inside collection literals too: ...flatten(item) spreads the result of the recursive call. printTree passes extra state (the indentation) down as a parameter, which is the usual way to track depth.
Recursive data types
When a type refers to itself, the functions that process it are naturally recursive. A classic example is an expression tree. With a sealed class hierarchy, the compiler checks that each recursive switch handles every kind of node:
sealed class Expr {}
class Num extends Expr {
final double value;
Num(this.value);
}
class Add extends Expr {
final Expr left, right;
Add(this.left, this.right);
}
class Mul extends Expr {
final Expr left, right;
Mul(this.left, this.right);
}
class Neg extends Expr {
final Expr operand;
Neg(this.operand);
}
double eval(Expr e) => switch (e) {
Num(:final value) => value,
Add(:final left, :final right) => eval(left) + eval(right),
Mul(:final left, :final right) => eval(left) * eval(right),
Neg(:final operand) => -eval(operand),
};
String show(Expr e) => switch (e) {
Num(:final value) => '$value',
Add(:final left, :final right) => '(${show(left)} + ${show(right)})',
Mul(:final left, :final right) => '${show(left)} * ${show(right)}',
Neg(:final operand) => '-${show(operand)}',
};
void main() {
// (2 + 3) * -4
final e = Mul(Add(Num(2), Num(3)), Neg(Num(4)));
print(show(e));
print(eval(e));
}
Output:
(2.0 + 3.0) * -4.0
-20.0
Each function mirrors the shape of the data: one case per subclass and a recursive call for each child expression. If you add a new subclass such as Sub, both eval and show stop compiling until you handle it.
Binary search trees and recursive generators
Tree operations like insert, search and height are short when written recursively. A sync* generator with yield* produces a lazy recursive traversal: yield* forwards every element of the iterable returned by the recursive call.
class Node<T extends Comparable<Object>> {
final T value;
Node<T>? left, right;
Node(this.value);
}
class BinaryTree<T extends Comparable<Object>> {
Node<T>? _root;
void insert(T value) => _root = _insert(_root, value);
Node<T> _insert(Node<T>? node, T value) {
if (node == null) return Node(value);
if (value.compareTo(node.value) < 0) {
node.left = _insert(node.left, value);
} else {
node.right = _insert(node.right, value);
}
return node;
}
bool contains(T value) => _contains(_root, value);
bool _contains(Node<T>? node, T value) {
if (node == null) return false;
final c = value.compareTo(node.value);
if (c == 0) return true;
return c < 0 ? _contains(node.left, value) : _contains(node.right, value);
}
int get height => _height(_root);
int _height(Node<T>? node) => node == null
? 0
: 1 + [_height(node.left), _height(node.right)].reduce((a, b) => a > b ? a : b);
// In-order traversal as a lazy, recursive generator.
Iterable<T> get inOrder => _inOrder(_root);
Iterable<T> _inOrder(Node<T>? node) sync* {
if (node == null) return;
yield* _inOrder(node.left);
yield node.value;
yield* _inOrder(node.right);
}
}
void main() {
final tree = BinaryTree<int>();
for (final n in [50, 30, 70, 20, 40, 60, 80, 35]) {
tree.insert(n);
}
print(tree.inOrder.toList());
print(tree.inOrder.take(3).toList());
print(tree.contains(35));
print(tree.contains(36));
print(tree.height);
}
Output:
[20, 30, 35, 40, 50, 60, 70, 80]
[20, 30, 35]
true
false
4
Because inOrder is lazy, take(3) stops the traversal after three values instead of visiting the whole tree. The bound T extends Comparable<Object> accepts int, String, DateTime and other comparable types (see Generics).
The private helpers (_insert, _contains, _height, _inOrder) are a common pattern: the public member has a simple signature and the recursive helper takes the extra parameter (the current node).
Memoization: avoiding repeated work
The textbook Fibonacci function makes two recursive calls, and those calls recompute the same values over and over, so the number of calls grows exponentially. Caching results in a map (memoization) makes it linear:
var calls = 0;
int fib(int n) {
calls++;
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
final _memo = <int, int>{};
int fibMemo(int n) {
calls++;
if (n < 2) return n;
return _memo[n] ??= fibMemo(n - 1) + fibMemo(n - 2);
}
void main() {
print('fib(32) = ${fib(32)}, calls: $calls');
calls = 0;
print('fibMemo(32) = ${fibMemo(32)}, calls: $calls');
calls = 0;
_memo.clear();
print('fibMemo(90) = ${fibMemo(90)}, calls: $calls');
}
Output:
fib(32) = 2178309, calls: 7049155
fibMemo(32) = 2178309, calls: 63
fibMemo(90) = 2880067194370816120, calls: 179
_memo[n] ??= expr evaluates expr only if n is not already in the map, stores the result and returns it. Seven million calls drop to 63.
fibMemo(90) still fits in a 64-bit int; fib(93) would not. Switch to BigInt for larger values.
Stack depth and StackOverflowError
Each call occupies space on the call stack until it returns. When the stack is exhausted, Dart throws StackOverflowError:
int depth = 0;
void dive() {
depth++;
dive();
}
int sumTo(int n) => n == 0 ? 0 : n + sumTo(n - 1);
int sumToLoop(int n) {
var total = 0;
for (var i = 1; i <= n; i++) {
total += i;
}
return total;
}
void main() {
try {
dive();
} on StackOverflowError catch (e) {
print('$e after roughly $depth calls');
}
print(sumTo(10000));
try {
print(sumTo(10000000));
} on StackOverflowError {
print('sumTo(10000000) overflowed the stack');
}
print(sumToLoop(10000000));
}
Output:
Stack Overflow after roughly 33444 calls
50005000
sumTo(10000000) overflowed the stack
50000005000000
The exact depth depends on the platform, the frame size of the function and how the code was compiled (JIT, AOT or JavaScript), so don't rely on a particular number. A few thousand levels are safe; millions are not.
Rewriting sumTo in tail-call form (int go(int n, int acc) => n == 0 ? acc : go(n - 1, acc + n);) would not help either, because Dart doesn't reuse the stack frame for tail calls. If the input size is unbounded, write a loop.
StackOverflowError is an Error, not an Exception: it signals a bug. Catching it is fine for a demonstration, but production code should avoid unbounded recursion rather than recover from it.
Converting recursion to iteration
Any recursive algorithm can be rewritten with an explicit stack stored on the heap. The heap is much larger than the call stack, so the iterative version handles inputs that would overflow:
class Node {
final String name;
final List<Node> children;
Node(this.name, [this.children = const []]);
}
// Recursive depth-first traversal.
void visit(Node node, List<String> out) {
out.add(node.name);
for (final child in node.children) {
visit(child, out);
}
}
// Same order, but with an explicit stack instead of the call stack.
List<String> visitIterative(Node root) {
final out = <String>[];
final stack = [root];
while (stack.isNotEmpty) {
final node = stack.removeLast();
out.add(node.name);
// Push children in reverse so the first child is processed first.
stack.addAll(node.children.reversed);
}
return out;
}
void main() {
final tree = Node('root', [
Node('a', [Node('a1'), Node('a2')]),
Node('b', [Node('b1')]),
]);
final out = <String>[];
visit(tree, out);
print(out);
print(visitIterative(tree));
// A degenerate tree that is 1,000,000 levels deep.
var deep = Node('leaf');
for (var i = 0; i < 1000000; i++) {
deep = Node('n$i', [deep]);
}
print(visitIterative(deep).length);
try {
visit(deep, []);
} on StackOverflowError {
print('recursive visit overflowed');
}
}
Output:
[root, a, a1, a2, b, b1]
[root, a, a1, a2, b, b1]
1000001
recursive visit overflowed
For depth-first traversal, push children in reverse order to visit them in the same order as the recursive version. For breadth-first traversal, use a Queue from dart:collection and take elements from the front instead.
A good rule: start with the recursive version because it is easier to get right, and convert it only if the depth can be large (user-controlled input, linked structures, degenerate trees).
Mutual recursion and local recursive functions
Functions can call each other recursively. Top-level functions and methods can be used before they are declared, so mutual recursion needs no forward declarations.
A named local function can call itself, which is handy for a helper that captures variables from the enclosing function (see Function scoping). An anonymous function has no name to call, so declare a late variable first and refer to it inside the function literal:
bool isEven(int n) => n == 0 ? true : isOdd(n - 1);
bool isOdd(int n) => n == 0 ? false : isEven(n - 1);
int countVowels(String text) {
const vowels = 'aeiou';
// A local function can call itself by name.
int go(int i) {
if (i == text.length) return 0;
return (vowels.contains(text[i]) ? 1 : 0) + go(i + 1);
}
return go(0);
}
void main() {
print(isEven(10));
print(isOdd(7));
print(countVowels('recursion in dart'));
// A function literal has no name, so declare the variable first.
late final int Function(int) digitSum;
digitSum = (n) => n < 10 ? n : n % 10 + digitSum(n ~/ 10);
print(digitSum(98765));
}
Output:
true
true
6
35
isEven/isOdd are for illustration only: they recurse n times, so a large n overflows the stack. Use n.isEven in real code.
Backtracking and divide and conquer
Many combinatorial problems are simplest as recursion: pick one option, recursively solve the rest, then try the next option. Writing them as sync* generators makes the results lazy, so you can stop as soon as you have what you need:
Iterable<List<T>> permutations<T>(List<T> items) sync* {
if (items.length <= 1) {
yield items;
return;
}
for (var i = 0; i < items.length; i++) {
final rest = [...items.take(i), ...items.skip(i + 1)];
for (final p in permutations(rest)) {
yield [items[i], ...p];
}
}
}
Iterable<List<T>> subsets<T>(List<T> items) sync* {
if (items.isEmpty) {
yield [];
return;
}
final [first, ...rest] = items;
for (final s in subsets(rest)) {
yield s;
yield [first, ...s];
}
}
void hanoi(int n, String from, String to, String via) {
if (n == 0) return;
hanoi(n - 1, from, via, to);
print('move disk $n from $from to $to');
hanoi(n - 1, via, to, from);
}
void main() {
print(permutations([1, 2, 3]).toList());
print(subsets(['a', 'b', 'c']).toList());
print(permutations(List.generate(10, (i) => i)).first);
hanoi(3, 'A', 'C', 'B');
}
Output:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
[[], [a], [b], [a, b], [c], [a, c], [b, c], [a, b, c]]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
move disk 1 from A to C
move disk 2 from A to B
move disk 1 from C to B
move disk 3 from A to C
move disk 1 from B to A
move disk 2 from B to C
move disk 1 from A to C
permutations of 10 items has 3,628,800 results, but .first computes only one because the generator is lazy. subsets uses list destructuring (final [first, ...rest] = items;, see Destructuring) to split the list.
Towers of Hanoi is the classic divide-and-conquer recursion: to move n disks, move the top n - 1 out of the way, move the largest disk, then move the n - 1 disks back on top of it.
Async recursion
async functions can recurse too; just await the recursive call. This walks a directory tree and adds up file sizes:
import 'dart:io';
Future<int> totalSize(Directory dir, [String indent = '']) async {
var total = 0;
final entries = await dir.list().toList()
..sort((a, b) => a.path.compareTo(b.path));
for (final entity in entries) {
final name = entity.uri.pathSegments.lastWhere((s) => s.isNotEmpty);
switch (entity) {
case Directory():
print('$indent$name/');
total += await totalSize(entity, '$indent ');
case File():
final size = await entity.length();
print('$indent$name $size');
total += size;
default:
break;
}
}
return total;
}
Future<void> main() async {
final root = await Directory.systemTemp.createTemp('recursion_demo');
await File('${root.path}/a.txt').writeAsString('hello');
await Directory('${root.path}/sub/deeper').create(recursive: true);
await File('${root.path}/sub/b.txt').writeAsString('dart!!');
await File('${root.path}/sub/deeper/c.txt').writeAsString('x' * 100);
print('total: ${await totalSize(root)} bytes');
await root.delete(recursive: true);
}
Output:
a.txt 5
sub/
b.txt 6
deeper/
c.txt 100
total: 111 bytes
Each await totalSize(...) finishes the whole subtree before moving on, so the output is in depth-first order. The recursion depth equals the depth of the directory tree, which is small in practice.
For simple cases, dir.list(recursive: true) does the walking for you and returns a flat Stream<FileSystemEntity>. Write your own recursion when you need per-directory totals, custom filtering (such as skipping .git) or indented output. See Async and Await for more on futures and streams.
Summary
- A recursive function needs a base case and a recursive case that moves toward it.
- Recursion fits recursive data: nested lists and maps, trees, JSON and sealed class hierarchies. Use
switchwith patterns to handle each case. - Use private helpers with an extra parameter (index, node, accumulator, indentation) to keep the public API simple.
sync*withyield*gives lazy recursive traversals and generators.- Memoize with a
Mapand??=when the same subproblems are solved repeatedly. - Dart has no tail call optimization. Deep recursion throws
StackOverflowError; use a loop or an explicit stack when depth is unbounded. - Rest patterns and
substringcopy data on every call; pass indexes for large inputs.