【发布时间】:2020-11-20 06:23:09
【问题描述】:
我是 Flutter 的新手,我正在尝试弄清楚如何在 main.dart 类中使用多个 ChangeNotifierProvider
我已经为此苦苦挣扎了好几个小时,但我似乎无法让它发挥作用。
多个 ChangeNotifierProvider 用于 Auth Screen 以及 Theme Changer。
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),
);
}
}
【问题讨论】:
-
这里有什么问题或错误?
-
我在 VS Code 中没有收到错误,但在应用程序中有一个带有黄色文字的红色屏幕,上面写着 >>>
Error: Could not find the correct Provider<ThemeChanger> above this MyApp widget This is likely happens becouse you used a BuildContext that does not include the provider of your choice. -
您是否将 Provider 小部件放在小部件树的顶部?
-
我不太明白你的意思。我在
MyApp Class上面的所有内容都是主要的main() function我已经更新了上面的代码