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?

Share:
1,313
Admin
Author by

Admin

Updated on December 22, 2022

Comments

  • Admin
    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
      Cread Dotson almost 4 years
      It 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
      Admin over 3 years
      Yeah thats exactly what was happening the last time I checked
  • Admin
    Admin over 3 years
    I 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
    Admin over 3 years
    In 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
    Abhishek over 3 years
    So 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.