This post will walk you through to generate the Fibonacci number sequence in Dart programming using various approaches.
Generate Fibonacci Sequence in Dart Programming
Getting Started
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. It usually starts with 0 and 1. The sequence goes:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Mathematically:
F(n) = F(n - 1) + F(n - 2)
With F(0) = 0 and F(1) = 1
The Fibonacci sequence is a classic example used in programming to teach recursion, loops, and algorithmic thinking. In Dart—a client-optimized programming language developed by Google, widely used in Flutter development—you can generate the Fibonacci sequence in multiple ways.
Here's how you can generate the Fibonacci number sequence in Dart using Iteration , Recursion and Generators approaches.
Using Iteration
The iterative method is efficient and avoids the overhead of recursion. Here's how you can generate the Fibonacci sequence up to a certain number of terms using a for
loop in Dart:
void main() {
int n = 20; // number of Fibonacci numbers to generate
List<int> sequence = [];
if (n >= 1) sequence.add(0);
if (n >= 2) sequence.add(1);
for (int i = 2; i < n; i++) {
sequence.add(sequence[i - 1] + sequence[i - 2]);
}
print('Fibonacci sequence up to $n terms are $sequence');
}
Output
Fibonacci sequence up to 20 terms are [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
Note:- This method is effective for larger number
Using Recursion
The recursive method is elegant but less efficient due to repeated calculations unless optimized (e.g., with memoization).
Dart Code Examplevoid main() {
int n = 10; // number of Fibonacci numbers to generate
print('Fibonacci sequence up to $n terms:');
for (int i = 0; i < n; i++) {
print(fibonacciRecursive(i));
}
}
int fibonacciRecursive(int n) {
if (n <= 1) return n;
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
Output
0
1
1
2
3
5
8
13
21
34
Note: Recursive methods can be slow for large n due to exponential time complexity. Consider memoization or using the iterative version for better performance.
Using Generators
This method lazily generates Fibonacci numbers using Dart's iterable:
Dart Code Example void main() {
Iterable<int> fibonacciGenerator([int maxCount = 10]) sync*
{
int a = 0, b = 1;
for (int i = 0; i < maxCount; i++)
{
yield a;
int temp = a;
a = b;
b = temp + b;
}
}
var sequence = fibonacciGenerator(10);
print('Fibonacci sequence: ${sequence.toList()}');
}
Output
Fibonacci sequence: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Summary
Dart makes it simple to implement classic algorithms like the Fibonacci sequence. For real-world applications, the iterative or memoized recursive approach is recommended due to performance. Whether you're building command-line tools or mobile apps with Flutter, understanding such algorithms strengthens your foundational programming skills.
Thanks