Flutter setstate on local variable not updating UI

645

the flag is resetted every time you call setState, beacuse the flag is in your generateListItem() widget,

I think you must set the bool in a list, so when you called setState, the state in the list of bool not resetted,

List<bool> flag = [];  // 

Widget generateListItem(int i){ 
flag.add(false);
return InkWell(
   onTap:(){
      setState((){
         flag[i]=true;
      })
   },
   child: Text(flag[i]? "Changed" : "Not Changed"),
);}
Share:
645
Bikram gurung
Author by

Bikram gurung

Updated on December 25, 2022

Comments

  • Bikram gurung
    Bikram gurung over 1 year

    So I tried to dynamically update an individual listview item. I am using a function to generate each item and I created a local variable in that function. I used setstate to update that variable but the UI is not updating. If i make the same variable global it works but i changes every listview items which I dont want. Does anyone have any tips on doing that? I am new to flutter and Sorry if this has been asked multiple times. I tried searching but couldnt find any solutions. This is a similar code for the item builder function.

    Widget generateListItem(){ 
        bool flag= false;
        return InkWell(
           onTap:(){
              setState((){
                 flag=true;
              })
           },
           child: Text(flag? "Changed" : "Not Changed"),
        );
    }
    
    • KuKu
      KuKu over 3 years
      When rebuild 'generateListItem' by setState(), flag is also reset. So always flag is false.
    • Bikram gurung
      Bikram gurung over 3 years
      Ohh.. That makes more sense now. Is there any way to update the item individually?
    • sameer kashyap
      sameer kashyap over 3 years
      Make it a variable inside the State class instead of inside the method. @Bikramgurung
    • Bikram gurung
      Bikram gurung over 3 years
      If I do that setstate changes every Item. I want to individually change the specific item.
    • KuKu
      KuKu over 3 years
      You need to control that value at top parent widget re-builded. "Page(here)[Stateful widget] - build() - 'generateListItem' widget..."
    • KuKu
      KuKu over 3 years
      Please show me your page source.
    • Bikram gurung
      Bikram gurung over 3 years
      Umm.. sorry for the trouble.. I figured it out after your explanation @KuKu. I created an object for child item and changed its variable. Thank you so much.
  • Jerry
    Jerry almost 3 years
    amazing! Map<String,bool> could be too.