ChangeNotifierProxyProvider getting null value

Issue

I am new to flutter.

In my application locale information is found when the user login.
So the idea is when the user login, it will pass the locale to AppLanguage.

I have written ChangeNotifierProxyProvider to get the locale inside authentication information and create a AppLanuage object

In the ChangeNotifierProxyProvider I am getting appLang as null. auth object is correctly NOT null.

What I don’t understand why I am getting null?

I did create it here right?

create: (_) => AppLanguage(),

shouldn’t it come as a parameter for the update?

Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: Auth()),
        ChangeNotifierProxyProvider<Auth, AppLanguage>(
            create: (_) => AppLanguage(),
            update: (ctx, auth, appLang) {
              print(auth);
              print(appLang);
            }
            //appLang.setLocale(auth == null ? 'en' : auth.language),
            ),
      ],
      child: Consumer2<Auth, AppLanguage>(
        builder: (ctx, auth, lang, child) => MaterialApp(
          title: 'Test App',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          locale: lang.appLocal,
          supportedLocales: [
            const Locale('en', 'US'),
            const Locale('ja', ''),
          ],
          localizationsDelegates: [
            AppLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          home: LandingView(),
        ),
      ),
    );
  }

Solution

I would try something like:

ChangeNotifierProxyProvider<Auth, AppLanguage>(
  create: (_) => AppLanguage(),
  update: (ctx, auth, appLang) => appLang..update(auth),
),
class AppLanguage with ChangeNotifier {
  void update(Auth auth) {
    // Do some custom work based on myModel that may call `notifyListeners`
  }
}

That way your child will be able to get the correct updated values when they’re available.

You can check more how to deal properly with that on the provider docs.

Answered By – Felipe Augusto

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *