ChangeNotifierProxyProvider获得空值

问题描述

我是新来的人。

在我的应用程序中,用户登录时会找到区域设置信息。 因此,想法是当用户登录时,它将语言环境传递给AppLanguage。

我写了ChangeNotifierProxyProvider来获取身份验证信息中的语言环境并创建一个AppLanuage对象

在ChangeNotifierProxyProvider中,我将appLang设置为null。 auth对象正确不为空。

我不明白为什么我会变成空?

我确实在这里创建了吗?

create: (_) => AppLanguage(),

它不应该作为更新的参数吗?

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,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(),);
  }

解决方法

我会尝试:

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`
  }
}

这样,您的孩子将可以在可用时获得正确的更新值。

您可以在provider docs上查看更多如何正确处理该问题的方法。