Search code examples
flutterdartbuilderflutter-provider

builder to update in ChangeNotifierProxyProvider on flutter


first thanks for check my question.

I'm a beginner and I have this code :

ChangeNotifierProxyProvider<Auth, ImgProvider>(
          builder: (ctx, auth, previousItem) => ImgProvider(
            auth.token,
            auth.userId,
            previousItem == null ? [] : previousItem.items,
          ),
        ),

𝑩𝒖𝒕 𝒅𝒖𝒆 𝒕𝒉𝒆 𝒄𝒉𝒂𝒏𝒈𝒆 𝒐𝒇 𝒃𝒖𝒊𝒍𝒅𝒆𝒓 𝒕𝒐 𝒄𝒓𝒆𝒂𝒕𝒆 𝒂𝒏𝒅 𝒖𝒑𝒅𝒂𝒕𝒆 𝒐𝒏

ChangeNotifierProxyProvider

𝑰 𝒅𝒐𝒏'𝒕 𝒏𝒐𝒘 𝒉𝒐𝒘 𝒆𝒙𝒂𝒄𝒕𝒍𝒚 𝒖𝒑𝒅𝒂𝒕𝒆 𝒎𝒚 𝒐𝒍𝒅 𝒄𝒐𝒅𝒆. 𝑰 𝒄𝒉𝒂𝒏𝒈𝒆𝒅 𝒊𝒕 𝒍𝒊𝒌𝒆 𝒕𝒉𝒊𝒔 :

ChangeNotifierProxyProvider<Auth, ImgProvider>(
          update: (ctx, auth, previousItem) => ImgProvider(
            auth.token,
            auth.userId,
            previousItem == null ? [] : previousItem.items,
          ),

𝑩𝒖𝒕 𝒗𝒊𝒔𝒖𝒂𝒍 𝒔𝒕𝒖𝒅𝒊𝒐 𝒕𝒆𝒍𝒍 𝒎𝒆 𝒕𝒉𝒂𝒕 "𝑻𝒉𝒆 𝒑𝒂𝒓𝒂𝒎𝒆𝒕𝒆𝒓 '𝒄𝒓𝒆𝒂𝒕𝒆' 𝒊𝒔 𝒓𝒆𝒒𝒖𝒊𝒓𝒆𝒅."

𝒘𝒉𝒂𝒕 𝑰 𝒘𝒂𝒏𝒕 𝒊𝒔 : " 𝒄𝒂𝒏 𝒚𝒐𝒖 𝒑𝒍𝒆𝒂𝒔𝒆 𝒄𝒐𝒓𝒓𝒆𝒄𝒕 𝒕𝒐 𝒎𝒆 𝒕𝒉𝒊𝒔 𝒄𝒐𝒅𝒆". 𝑷𝒍𝒆𝒂𝒔𝒆 𝑯𝒆𝒍𝒑!


Solution

  • the solution is to change it like this :

     ChangeNotifierProxyProvider<Auth, ImgProvider>(
              create: (ctx) => ImgProvider(),
              update: (ctx, auth, previousItem) => previousItem
                ..receiveToken(
                    auth, previousItem == null ? [] : previousItem.items),
            ), 
    

    and create a function in ImgProvider() like this :

    void receiveToken(Auth auth, List<ImgVar> items) {
        authToken = auth.token;
        userId = auth.userId;
        _items = items;
      }