Provider/ChangeNotifier:在构建窗口小部件后设置状态 [英] Provider/ChangeNotifier: Set state after Widget is build

查看:49
本文介绍了Provider/ChangeNotifier:在构建窗口小部件后设置状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Provider/ChangenNotifier模式处理状态,如在官方文档中.

Im using the Provider/ChangenNotifier Pattern to handle state as described in the official docs.

我有一个状态字段,要在构建小部件后设置.但是,如果我尝试在build方法中进行设置.我收到错误消息:

I have a state field which I want to set after a Widget is build. However if I try to set in in the build method. I get an Error:

在构建过程中调用

setState()或markNeedsBuild().

setState() or markNeedsBuild() called during build.

我在哪里可以这样称呼:

Where can I call something like:

var state = Provider.of<StateModel>(context);
state.field = 'new Val';

推荐答案

您无法在构建期间设置状态,如果要测试状态更改,请将此代码放入 state.field ='new Val'; 之类的按钮事件,例如 FloatActionButton 或构建完成后的事件(带有Future.delayed或添加post fram回调,请参见

You can not set the state during a build, if you want to test a change of state, put this code state.field = 'new Val'; inside a button event, like FloatActionButton or a event after build completed (with Future.delayed or add post fram callback, see Is there any callback to tell me when "build" function is done in Flutter?)

警告:如果您在state.field集中调用 notifyListeners(),并使用提供程序监听小部件中的更改,则将导致无限的重建周期...这是您无法在构建过程中设置状态的另一个原因...

Warning If you are invoking notifyListeners() inside your state.field set, and listening changes in your widget with provider, It would cause an infinite cycle of rebuild... this is another reason that you can not set state during build...

这篇关于Provider/ChangeNotifier:在构建窗口小部件后设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆