I have a problem & dilemmas in setting dependencies with Provider packages.
My code:
providers: [
ChangeNotifierProvider<AuthModel>(
builder: (context) => AuthModel(userRepository: UserRepository())),
ChangeNotifierProxyProvider<AuthModel, AppModel>(
initialBuilder: (_) => AppModel(),
builder: (_, auth, app) => app..authModel = auth,
),
],
Using ChangeNotifierProxyProvider
, changes on authModel makes builder on ChangeNotifierProxyProvider
to run every time. AuthModel is a ChangeNotifier setting it once as dependency would be enough.
The questions:
On every code rebuild(providers is set on build method) does the
ChangeNotifierProvider<AuthModel>(
builder: (context) => AuthModel(userRepository: UserRepository()))
recreates the AuthModel instance?
On every change on AuthModel the
ChangeNotifierProxyProvider<AuthModel, AppModel>(
initialBuilder: (_) => AppModel(),
builder: (_, auth, app) => app..authModel = auth,
),
builder assigns again? AuthModel is an ChangeNotifier, doesnt make sense of reassign.
ChangeNotifierProxyProvider
builder runs again?The default constructor of ChangeNotiferProvider
will call builder
once and only once.
ChangeNotiferProxyProvider
, on the other hand, will call builder
again every time one of its dependencies updates.
But it is completely fine. Having builder
being called again doesn't mean that dependents have to update. The update is performed only if the builder
calls notifyListeners
on the notifier.
Which means your notifier can filter updates like so:
class MyNotifier with Notifier {
A _a;
A get a => _a;
set a(A value) {
// don't unnecessarily call `notifyListeners` if nothing changed
if (value != _a) {
_a = value;
notifyListeners();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With