mhannani
mhannani

Reputation: 502

Flutter - ChangeNotifierProxyProvider package

I have been using the Provider package 3.1.0 version last year to share value between providers ,like that :

...
return MultiProvider(
  providers: [
    ChangeNotifierProvider.value(
      value: Auth(),
    ),
    ChangeNotifierProxyProvider<Auth, Products>(
      builder: (ctx, auth, previousProd) => Prod(
            auth.cred,
            previousProd,
          ),
    ),
    ),
  ],)
...

Now with the version 4.1.3 two parameters are required : create and update

And i got stuck editing my application , I tried that :

...
return MultiProvider(
  providers: [
    ChangeNotifierProvider.value(
      value: Auth(),
    ),
    ChangeNotifierProxyProvider<Auth, Products>(
      update: (ctx, auth, previousProd) => Prod(
            auth.cred,
            previousProd,
          ),
    ),
    ),
  ],)
...

It shows that the create parameter is required as i said But i cannot figure out how to use that parameter ,

Can someone please help me ,i would appreciate that , Thanks !

Upvotes: 0

Views: 1342

Answers (1)

EdwynZN
EdwynZN

Reputation: 5601

ProxyProvider doesn't require the create parameter but ChangeNotifierProxyProvider does, to avoid creating a ChangeNotifier each time (with ProxyProvider there is no problem because is a simple class with no listeners). The create is called once, while the update can be called multiple times, so the code for a ChangeNotifierProxyProvider should look like this

 ChangeNotifierProxyProvider<Auth, Products>(
   create: (_) => Prod(),
   update: (_, auth, product) => product..credential = auth.cred,
   //instead of creating a new object Prod(), just reuse the existing one and set the new values
   child: ...
 )

And the Prod class

class Prod extends ChangeNotifier{
  Credential _cred;

  Prod(){
    //if you want to initialize some values
  }

  set credential(Credential credential) => _cred = credential;
  //or some other logic you do here with the auth.cred
}

Now each time Auth change and notifies the ProxyProvider it will reuse the same object created in create and just change the parameter credential (_cread)

Upvotes: 1

Related Questions