[英]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 ).事情是这样的:我在一个 class 中有三个按钮,它改变了一个变量 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.但是在第二个片段中,小部件不知道是否发生了变化,并且它没有再次调用 buildcontext ......我不知道如何克服这个问题。 I have tried valuelistenablebuilder but in vain.
我试过valuelistenablebuilder但徒劳无功。 Maybe i dont know how to use it in the loop (i am using foodcategory as an int (iterator)).
也许我不知道如何在循环中使用它(我使用 foodcategory 作为 int(迭代器))。
it happned to be that i was sing valuelistenable builder in a wrong way.碰巧是我以错误的方式唱了valuelistenable builder。
It is easy.这很容易。 Just mark the variable and changes as valueNotifier.
只需将变量和更改标记为 valueNotifier。 In my case, i needed to mark foodCategory as a valueNotifer.
就我而言,我需要将 foodCategory 标记为 valueNotifer。
Than, i needed to wrap the Widget (in my case column widget) as ValueListenableBuilder.比,我需要将小部件(在我的情况下是列小部件)包装为 ValueListenableBuilder。 This solved my issue.
这解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.