你好,我在应用程序中使用Multiprovider,其中一个提供程序是GlobalProvider,其中包含有关应用程序范围状态的信息,我想使用该提供程序来切换主题的亮度。但是,当我尝试运行附加代码时出现错误。
void main() => runApp(NextActionApp());
class NextActionApp extends StatelessWidget {
const NextActionApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<GlobalBloc>.value(
value: GlobalBloc(),
),
],
child: MaterialApp(
title: 'App',
home: InboxPage(),
theme: ThemeData(
primarySwatch: Colors.deepPurple,
brightness: Provider.of<GlobalBloc>(context).isDarkModeEnabled
? Brightness.dark
: Brightness.light,
),
),
);
}
}
答案 0 :(得分:0)
我用以下方式解决了这个问题:
void main() async {
final prefs = new PreferenciasUsuario();
await prefs.initPrefs();
setupLocator();
runApp(
MultiProvider(providers: [
ChangeNotifierProvider<ThemeProvider>(
create: (_) => ThemeProvider(isLightTheme: true),
),
],
child: MyApp(),
));
}
class MyApp extends StatelessWidget {
final prefs = new PreferenciasUsuario();
@override
Widget build(BuildContext context) {
final themeProvider = Provider.of<ThemeProvider>(context);
return ChangeNotifierProvider<ThemeProvider>(
create: ( BuildContext context ) => ThemeProvider(isLightTheme: true),
child: CustomeProvider(
child: Consumer<ThemeProvider>(builder: ( context, model, __ ){
return new MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
initialRoute: prefs.isLogged?'home':'login',
routes: {
'login' : ( BuildContext context ) => LoginPage(),
'home' : ( BuildContext context ) => HomePage(),
'config' : ( BuildContext context ) => ConfiguracionesPage(),
},
theme: model.getThemeData
);
})
)
);
}
}
答案 1 :(得分:0)
我遇到了同样的问题,并用builder
的{{1}}方法解决了。
部分
MultiProvider
成功了!
下面是一个完整的示例:
builder: (context, child) {
return MaterialApp ...
}