Search code examples
flutterdartflutter-providerdart-pubflutter-change-notifier

Flutter ChangeNotifierProxyProvider ChangeNotifier in create needs arguments


I am in the process of programming my app and need to use a ChangeNotifierProxyProvider. Unfortunately my ChangeNotifier (in this case Entries) needs 3 positional arguments. I already managed to specify the arguments in update, but how can I do it in create?

I would be very happy about an answer, because I can't find anything on the internet.

Hey! I am in the process of programming my app and need to use a ChangeNotifierProxyProvider. Unfortunately my ChangeNotifier (in this case Entries) needs 3 positional arguments. I already managed to specify the arguments in update, but how can I do it in create?

I would be very happy about an answer, because I can't find anything on the internet.

Here is my code for the providers: []:

providers: [
   ChangeNotifierProvider.value(value: Auth()),
   ChangeNotifierProxyProvider<Auth, Entries>(
      create: (_) => Entries(),
      update: (_, auth, previousEntries) => Entries(
        auth.token,
        auth.userId,
        previousEntries == null ? [] : previousEntries.items,
     ),
   ),
], 

Solution

  • In this question ChangeNotifierProxyProvider not initiated on build the author did this:

    return MultiProvider(
            providers: [              
              ChangeNotifierProvider<WhatEver>(create: (context) => WhatEver()),
              ChangeNotifierProxyProvider<AuthProvider, ProductList>(
                create: (_) => ProductList(Provider.of<AuthProvider>(context, listen: false)),
                update: (_, auth, productList) => productList..reloadList(auth)
              ),
            ],
    

    i.e. he used Provider.of to get the AuthProvider required by his ProductList. You could use a similar approach, but I expect it will need to be created in a parent context.

    Note that the answer to the other question pointed out the need to use lazy: false. So here is your example:

      Widget build(BuildContext context) {
        return ChangeNotifierProvider(
          create: (context) => AuthService(),
          builder: (context, _) => MultiProvider(
            providers: [
              ChangeNotifierProxyProvider<AuthService, Entries>(
                create: (_) =>
                    Entries(Provider.of<AuthService>(context, listen: false).user),
                lazy: false,
                update: (_, auth, previousEntries) => Entries(
                  auth.user,
                ),
              ),
            ],
            child: MaterialApp(
    

    Obviously you no longer need to use MultiProvider, but it does not hurt.