Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Provider - ChangeNotifierProxyProvider setting dependencies

Tags:

flutter

dart

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:

  1. On every code rebuild(providers is set on build method) does the

    ChangeNotifierProvider<AuthModel>(          
            builder: (context) => AuthModel(userRepository: UserRepository()))
    

recreates the AuthModel instance?

  1. 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.

  1. On every rebuild, ChangeNotifierProxyProvider builder runs again?
like image 943
cosinus Avatar asked Aug 26 '19 08:08

cosinus


1 Answers

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();
    }
  }
}
like image 136
Rémi Rousselet Avatar answered Nov 15 '22 10:11

Rémi Rousselet