What is SetState in Flutter?

When working on flutter projects, the SetState function is one of the most critical methods to know. It will not function on Stateless widgets because it only exists on state objects. It instructs flutter to run the code in a specific calback and then redraws all widgets that rely on the state for configuration. The only argument to this method is a void callback.

The State object is housed in the _MyHomePageState widget in my previous blog, and its children interact with and rely on it. When you push the button, it invokes a method supplied by _MyHomePageState. That method calls setState, which calls _MyHomePageState.build again, redrawing the widgets whose configurations have changed.

That’s all there is to setState, but keep in mind that it’s async code. Because you don’t want Flutter to redraw something before the data it’s supposed to display has resolved, async work should be done before calling setState. If you’re getting a gif from an online gif API, for example, you don’t want to execute setState until the picture is ready to display.

Leave a Comment

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