How to change values in OnTap Function when used in a for loop in Flutter
1,313
Your code is working just fine.
List<Widget> abc = [];
@override
Widget build(BuildContext context) {
for (int a = 0; a < 5; a++) {
abc.add(FlatButton(
onPressed: () {
print(a);
},
child: Text("Hello - $a")));
}
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView.builder(
itemCount: abc.length,
itemBuilder: (context, index) {
return abc[index];
},
),
),
);
And how can it return 5
when the max value of a
is 4?
Author by
Admin
Updated on December 22, 2022Comments
-
Admin over 1 year
This is how my code looks like:
List<Widgets> abc = []; for(int a = 0;a<5;a++) { abc.add(FlatButton(onTap:(){ print(a);}, child:Text("Hello - ${a}") ) ); }
When user clicks on "Hello - 2" Button, I want the output on console to be 2 but the output displayed is 5.
I have simplified the original problem in the form of this small programming question.I have checked a lot on internet but was unable to get any answer. Help me out please!!
-
Cread Dotson almost 4 yearsIt looks like you're not storing the a variable for each button. You're just converting it to a string to make the button name but when the button is pushed "a" still refers to your incrementing variable.
-
Admin over 3 yearsYeah thats exactly what was happening the last time I checked
-
-
Admin over 3 yearsI don't know why and how this is working fine but last when I checked it was not storing the value of a. It was just taking the last value of a which was somehow 5. At that time the system may be taking garbage value (idk, it could be).
-
Admin over 3 yearsIn the original problem, I was displaying the result in the form of a List and clicking on those result tiles, I wanted to animate to new Screen using Hero widget. So I made a function with a for loop and was using loop variable values as a tag for hero widget but every time the tag was taking the value '5' if the above-mentioned loop was used. I had no idea why this was happening.
-
Abhishek over 3 yearsSo is this solution working for you ? or something else has to be addressed here? Update your question if you are having problems or accept the answer if this answer correctly addresses and solves your problem.