You cannot control whether or not a widget is being rebuilt. This can happen in many situations you don't have control over:
- The screen size changes
- Some dependencies changed (ex: theme)
- A parent rebuilds multiple times (for example because of an animation)
- etc
Checkout this answer from Rémi Rousselet
The build method is designed in such a way that it should be pure/without side effects.
The problem you are facing is that your build method has side effects/is not pure, making extraneous build calls troublesome.
Instead of preventing build calls, you should make your build method pure, so that it can be called anytime without impact.
So if an extra build brings issues in your stateful widget, it means the build method is not pure and needs to be made pure.
You can use initState
, didChangeDependencies
, or didUpdateWidget
, and store, for example, an API call in the state.