简体   繁体   English

如何从另一个小部件 class - Flutter 更新小部件树

[英]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.

相关问题 Flutter:如何从另一个有状态类更新 UI 状态小部件 - Flutter:How to update a UI -stateful widget from another stateful class 如何从另一个小部件的内置颤振更新小部件状态 - How to update a widget state from another widget's build in flutter 如何使用 Flutter 和 Dart 中的下拉菜单从另一个小部件更新小部件? - How To Update A Widget from Another Widget with A DropDown in Flutter and Dart? 如何从 Flutter 中的另一个小部件滚动小部件 - How to scroll a widget from another widget in Flutter flutter,如何判断树中是否有另一个小部件 - flutter, How to judge whether another widget is in the tree 如何使用全局密钥从 Flutter 中的另一个小部件更新小部件 state? - How to update a widget state from another widget in Flutter using global Key? Flutter:在小部件树外的另一个 class 中调用 Provider 方法 - Flutter: Invoking Provider method in another class outside of the widget tree Flutter-如何在另一个类上显示/隐藏小部件 - Flutter - How to Show/Hide Widget on another Class Flutter - 如何在搜索时将搜索文本从一个小部件传递到另一个 class 小部件? - Flutter - How to pass search text from one widget to its another class widget while searching? Flutter Bloc 如何从 Widget 本身更新 BlocBuilder 中的 Widget? - Flutter Bloc How to update Widget in BlocBuilder from the Widget itself?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM