When should I initialize the data?
If I have a model provide by Provider, and I want to use it in the sub Widget。 I need to get the Model by using Provider.of(context) in didChangeDependence like this.
@override
void didChangeDependencies() {
super.didChangeDependencies();
final counter = Provider.of(context);
counter.increment();
}
But this will cause side effects, causing counter.increment to be called again. I check the source code and find this comment.
/// If [listen] is true (default), later value changes will trigger a new
/// [State.build] to widgets, and [State.didChangeDependencies] for
/// [StatefulWidget].
So how can I initialize data without side effects?
@rrousselGit hi Remi , could you give some advice ?
This code is relatively unsafe. There's more than one reason for didChangeDependencies to be called.
You probably want something similar to:
MyCounter counter;
@override
void didChangeDependencies() {
final counter = Provider.of<MyCounter>(context);
if (conter != this.counter) {
this.counter = counter;
counter.increment();
}
}
This should trigger increment only once.
thanks man
Most helpful comment
This code is relatively unsafe. There's more than one reason for
didChangeDependenciesto be called.You probably want something similar to:
This should trigger
incrementonly once.