polina-c
polina-c

Reputation: 7077

Flutter app: how about changing the state inside 'build'?

I am new to Flutter.

I need to change state in the method 'build'. I am wandering if I need to do it with setState. Also can I initiate navigation in build? On one hand, setState will signal that the component should rebuild. As I am already building it, and building it in a right way, do I need to initiate another rebuilding? If yes, should I exit the method 'build' right after invoking setState?

Upvotes: 2

Views: 690

Answers (2)

polina-c
polina-c

Reputation: 7077

State changes and navigation should be performed before build: either in initState or in event handlers.

Upvotes: 0

Rémi Rousselet
Rémi Rousselet

Reputation: 277057

The premise is false: You shouldn't change the state inside build.

There are clear life-cycles that should be used to do these state changes. Depending on what change accured, you may want to use:

  • didChangeDependencies, for changes related to InheritedWidgets
  • didUpdateWidget, when the created of this widget rebuilt it with new variables

You should use these over build to do custom work instead.

Upvotes: 2

Related Questions