我是新手,我试图弄清楚如何在main.dart
类中使用多个ChangeNotifierProvider。
我已经为此苦苦挣扎了好几个小时,但我似乎无法使它正常工作。
多个ChangeNotifierProvider用于认证屏幕以及主题转换器。
void main() async {
var delegate = await LocalizationDelegate.create(
fallbackLocale: 'en_US', supportedLocales: ['en_US', 'sv']);
runApp(LocalizedApp(delegate, MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Provider.of<ThemeChanger>(context);
var localizationDelegate = LocalizedApp.of(context).delegate;
FlutterStatusbarcolor.setStatusBarWhiteForeground(false);
return MultiProvider(
providers: [
ChangeNotifierProvider.value(
value: Auth(),
),
ChangeNotifierProvider<ThemeChanger>(
create: (_) => ThemeChanger(CustomThemes.lightTheme.copyWith(
textTheme:
CustomThemes.textTheme(CustomThemes.lightTheme.textTheme))),
child: MaterialAppWithTheme(),
)
],
child: Consumer<Auth>(
builder: (ctx, auth, _) => MaterialApp(
title: translate('appbar.title_app'),
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
localizationDelegate
],
supportedLocales: localizationDelegate.supportedLocales,
locale: localizationDelegate.currentLocale,
theme: theme.getTheme(),
color: Theme.of(context).primaryColor,
home: auth.isAuth ? MdDrawer(title: AppStrings.appTitle) : AuthenticationScreen(),
),
),
);
}
}
class MaterialAppWithTheme extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Provider.of<ThemeChanger>(context);
return MaterialApp(
title: AppStrings.appTitle,
debugShowCheckedModeBanner: false,
theme: theme.getTheme(),
color: Theme.of(context).primaryColor,
home: MdDrawer(title: AppStrings.appTitle),
);
}
}
答案 0 :(得分:0)
仅当窗口小部件由提供者包装或为该提供者所包装的窗口小部件的子代时,才可以在对象中使用对象的提供者。这就是通过将提供程序放置在窗口小部件树的顶部。
在此,您已在小部件内使用了MultiProvider,并且final theme = Provider.of<ThemeChanger>(context);
位于小部件中未被提供者包装的部分。
因此,与其直接创建主题变量,不如直接使用
theme: Provider.of<ThemeChanger>(context).getTheme();