hello guys this program display Fibonacci series in list views but it display first two numbers 1 -1 only in Fibonacci series the number equal the sum of the last two numbers example 5 equal 3+2 and 8 equal 3+5 I want program display infinite Fibonacci series what shall I do to make the list infinite Fibonacci series ? there is the code to know the cause of displaying 1-1 only in the list
import 'package:flutter/material.dart';
void main() async {
final numbers = FibonacciNumbers();
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('Fibonacci List'),
),
body: FibonacciListView(numbers),
),
),
);
}
class FibonacciNumbers {
final cache = {0: BigInt.from(1), 1: BigInt.from(1)};
BigInt get(int i) {
if (!cache.containsKey(i)) {
cache[i] = get(i - 1) + get(i - 2);
}
return cache[i]!;
}
}
class FibonacciListView extends StatelessWidget {
final FibonacciNumbers numbers;
const FibonacciListView(this.numbers, {super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
title: Text('Fibonacci List'),
),
body: ListView.builder(
itemCount: numbers.cache.length,
itemBuilder: (context, i) {
return ListTile(
title: Text('${numbers.get(i).toString()}'),
onTap: () {
final snack = SnackBar(
content: Text('${numbers.get(i)} is #$i in the Fibonacci sequence!'),
);
ScaffoldMessenger.of(context).showSnackBar(snack);
},
);
},
),
);
}
}
display the Fibonacci series 0,1,1,2,3,5,8,13 and so on.
2
Answers
You need to edit many things. I edited your code. This is 100% working solution.
By the way, I deleted an app bar and a scaffold object. Because you put the Scaffold inside another Scaffold in you code in question.
The only issue with your code is you are providing length of list i.e.
numbers.cache.length
. As @mmcdon20 mentioned in comment, if you remove it, your code will run fine as it is.There is another issue in your solution. As the snackbar message should consider that list index start with 0 but the real world sequence starts with index 1.
Modified your code a little bit