Provider: The right time to initialize the data in Provider

Created on 5 Jul 2019  Â·  3Comments  Â·  Source: rrousselGit/provider

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?

Most helpful comment

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.

All 3 comments

@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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mhd-barikhan picture mhd-barikhan  Â·  5Comments

usherwalce picture usherwalce  Â·  5Comments

MaxTenco picture MaxTenco  Â·  5Comments

ykaito21 picture ykaito21  Â·  3Comments

sanekyy picture sanekyy  Â·  5Comments