[英]Two providers in one Widget - Flutter
我有这个问题。 在我的应用程序中,我使用Provider package
来管理登录 State。 在 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...
甚至在一个小部件中使用两个不同的 Providers(例如,将我的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(),
...
您可以使用 MultiProvider 代替 ChangeNotifierProvider。 在这里阅读更多。
当您在创建ChangeNotifierProvider
class 之后使用context
时,就会出现这种类型的错误。
同样,如果使用Scaffold
的context
来 showDialog 会给出类似的错误。 这是解释为什么会发生这种情况的答案
对于此包装,您在Builder
Class 中的MaterialApp
Widget 将等待 class 首先构建,然后调用Provider.of<T>(context)
方法。
Builder(
builder: (context) {
return 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(),
},
);
},
),
对于同一小部件中的两个提供者。
使用MultiProvider
。
这是我的一个应用程序的代码。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provider(
create: (_) => locator<FAuthService>(),
builder: (context, _) {
return MultiProvider(
child: MaterialApp(
onGenerateRoute: Router.onGenerateRoute,
initialRoute: initialRoute,
navigatorKey: locator<NavigationService>().globalKey,
debugShowCheckedModeBanner: false,
title: 'Demo',
theme: ThemeData(
primaryColor: Colors.black,
),
),
providers: [
ChangeNotifierProvider<HomeVM>(
create: (_) => locator<HomeVM>(),
),
ChangeNotifierProvider<LoginVM>(
create: (context) => locator<LoginVM>(),
),
],
);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.