[英]How to i use the context built in Flutter MultiProvider, inside its child?
I am trying to use the MyTheme provider to set the theme value in MaterialApp, by using MultiProvider.我正在尝试使用 MyTheme 提供程序通过使用 MultiProvider 在 MaterialApp 中设置主题值。 However the MaterialApp is unable to access the MyTheme provider.但是 MaterialApp 无法访问 MyTheme 提供程序。
I am trying to change the theme by using a button inside the app, which will update the provider and in turn change the theme for the whole app.我正在尝试通过使用应用程序内的按钮来更改主题,这将更新提供程序并反过来更改整个应用程序的主题。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => Result(),
),
ChangeNotifierProvider(
create: (context) => MyTheme(),
),
],
child: MaterialApp(
home: TasksScreen(),
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: context.watch<MyTheme>().currentTheme(),
),
);
}
}
I believe I am unable to access it because the consumer and provider is on the same level, but I am not sure how to go about it.我相信我无法访问它,因为消费者和提供者处于同一级别,但我不确定如何去做。
class MyTheme with ChangeNotifier {
static bool _isDark = true;
ThemeMode currentTheme() {
return _isDark ? ThemeMode.dark : ThemeMode.light;
}
void switchTheme() {
_isDark = !_isDark;
notifyListeners();
}
}
How can I access the MyTheme Provider in the child of the MultiProvider?如何在 MultiProvider 的子节点中访问 MyTheme Provider?
If it is not possible, what is the better way to do it?如果不可能,那么更好的方法是什么?
Wrap MaterialApp in a Builder在构建器中包装 MaterialApp
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => Result(),
),
ChangeNotifierProvider(
create: (context) => MyTheme(),
),
],
child: Builder(
builder: (context) => MaterialApp(
home: TasksScreen(),
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: context.watch<MyTheme>().currentTheme(),
),
),
);
}
}
使用提供者
var theme = Provider.of<MyTheme>(context, listen: false).currentTheme();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.