Flutter setstate on local variable not updating UI
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"),
);}
Bikram gurung
Updated on December 25, 2022Comments
-
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 over 3 yearsWhen rebuild 'generateListItem' by setState(), flag is also reset. So always flag is false.
-
Bikram gurung over 3 yearsOhh.. That makes more sense now. Is there any way to update the item individually?
-
sameer kashyap over 3 yearsMake it a variable inside the
State
class instead of inside the method. @Bikramgurung -
Bikram gurung over 3 yearsIf I do that setstate changes every Item. I want to individually change the specific item.
-
KuKu over 3 yearsYou need to control that value at top parent widget re-builded. "Page(here)[Stateful widget] - build() - 'generateListItem' widget..."
-
KuKu over 3 yearsPlease show me your page source.
-
Bikram gurung over 3 yearsUmm.. 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 almost 3 yearsamazing!
Map<String,bool>
could be too.