简体   繁体   中英

How to update widget tree from another widget class - Flutter

I am facing problem to re-render the page when a variable changes in one class/widget (both parent and child widgets are stateful classes).

Here is how it goes: I have three buttons in one class which changes a variable state ( foodCategory ).

int foodCategory = 0;
// down in the elevated button body - i am updating the variable
setState(() {
          foodCategory = 1;});

While in the other widget, i am using this variable to perform certain actions:

for (var item in foodItems.values.elementAt(foodCategory))
                GestureDetector(........ and so on...

However in the second snippet, the widget dose not know if there has been a change and it is not calling the buildcontext again... I am not sure how to overcome this problem. I have tried valuelistenablebuilder but in vain. Maybe i dont know how to use it in the loop (i am using foodcategory as an int (iterator)).

it happned to be that i was sing valuelistenable builder in a wrong way.

It is easy. Just mark the variable and changes as valueNotifier. In my case, i needed to mark foodCategory as a valueNotifer.

Than, i needed to wrap the Widget (in my case column widget) as ValueListenableBuilder. This solved my issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM