Reputation: 905
I want to show all the natural numbers between the two inputs provided by user into Text widget but getting the above error. Here's the Snippet of my code:
List<int> naturalNumber = []; <------Initialization of natural number(in the state class)
onPressed:(){
setState(() {
int X = int.parse(valueOfX.text);
int Y = int.parse(valueOfY.text);
difference = Y-X;
if(X>0 && Y>0 && Y-X>1 &&Y-X<50){
for(var i=0;i<=difference;i++){
naturalNumber[i] = X;
X=X+1;
}
for(int j=0;j<=naturalNumber.length;j++)
{
print(naturalNumber[j]);
}
shouldDisplay = !shouldDisplay;
}
}
}
Here I want to print all the natural number between user input :
shouldDisplay?Column(
children: [
for ( var i in naturalNumber ) Text(i.toString())
],
):Spacer()
Upvotes: 1
Views: 164
Reputation: 1140
Try this
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
List<int> numbers = getAllNaturalNumbers(5, 10);
return ListView.builder(
itemCount: numbers.length,
itemBuilder: (_cont, _pos) => Text('${numbers[_pos]}'));
}
List<int> getAllNaturalNumbers(int first, int second) {
return first > second
? List.generate(first - second + 1, (val) => second + val)
: List.generate(second - first + 1, (val) => first + val);
}
}
Upvotes: 0
Reputation: 2956
Try using below Code:
import 'package:flutter/material.dart';
void main() =>
runApp(MaterialApp(home: CounterDemo()));
class CounterDemo extends StatefulWidget {
@override
_CounterDemoState createState() => _CounterDemoState();
}
class _CounterDemoState extends State<CounterDemo> {
var shouldDisplay = false;
int x = 20;
int y = 19;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Counter Demo"),
),
body: SingleChildScrollView(
child: Column(
children: [
RaisedButton(
child: const Text("Show Values"),
onPressed:()=>setState(() {
shouldDisplay = !shouldDisplay;
}),
),
shouldDisplay
? ListView.builder(
shrinkWrap: true,
itemCount: (x - y).abs() + 1,
itemBuilder: (BuildContext ctxt, int index) {
var highestValue =x>y?x:y;
var lowestValue =x<y?x:y;
// in ascending form from 1 to 10
return Center(child: Text((lowestValue + index).abs().toString()));
// in descending form from 10 to 1
// return Center(child: Text((highestValue - index).abs().toString()));
})
: Container(),
],
),
),
);
}
}
This works for me. :)
Upvotes: 2