flutter: State is lost on Hot Reload when using Provider
The build method is designed in such a way that it should be pure/without side effects. This is because many external factors can trigger a new widget build, such as:
Route pop/push
Screen resize, usually due to keyboard appearance or orientation change
Parent widget recreated its child
An InheritedWidget the widget depends on (Class.of(context) pattern) change
This means that the build method should not trigger an http call or modify any state.
How is this related to the question?
The problem you are facing is that your build method has side-effects/is not pure, making extraneous build call troublesome.
Instead of preventing build call, you should make your build method pure, so that it can be called anytime without impact.
In the case of your example, you'd transform your widget into a StatefulWidget then extract that HTTP call to the initState of your State:
ChangeNotifierProvider(
create: (_) => UserService(),
),
You should not use ChangeNotifierProvider.value
. Instead use the default constructor:
ChangeNotifierProvider(
builder: (_) => UserService(),
)
Otherwise, your build method is impure and you'll have issues like described in How to deal with unwanted widget build?