【发布时间】:2020-08-14 08:15:56
【问题描述】:
我有这个问题。在我的应用程序中,我使用Provider package 来管理登录状态。在 MaterialApp 中,我还想管理某种用户配置,在本例中是主题选择。
如果我尝试使用两次 Provider.of<LoginService>(context) 我会收到此错误:
Could not find the correct Provider<LoginService> above this MyApp Widget
This likely happens because you used a `BuildContext` that does not include the provider
of your choice.
如何在 Provider 中多次使用 Provider.of... 或什至在一个小部件中使用两个不同的 Provider(例如,将我的 LoginService 和我的 UserconfigService 分开)?
谢谢!
实际代码:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<LoginService>(
create: (context) => LoginService(),
child: MaterialApp(
title: 'My App',
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
routes: {
'/': (BuildContext context) {
var state = Provider.of<LoginService>(context);
if (state.isLoggedIn()) {
return HomeScreen();
} else {
return LoginScreen();
}
},
MentorScreen.id: (BuildContext context) => MentorScreen(),
},
)
);
}
我的目标:
child: MaterialApp(
title: 'MyApp',
debugShowCheckedModeBanner: false,
theme: state.isDarkThemeEnabled() == true ? ThemeData.dark() : ThemeData.light(),
...
【问题讨论】:
标签: android flutter dart state provider