Provider/ChangeNotifier: Set state after Widget is build

Issue

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

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() or markNeedsBuild() called during build.

Where can I call something like:

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

Solution

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?)

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…

Answered By – Renê Guilherme Nucci

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *