I\'ve created an app and I have used MultiProvider but it doesn\'t work when I use it inside MaterialApp
I want to use it to change app theme color but
it
The following test code work without error, you can test with your case
Use Consumer
to wrap MaterialApp
code snippet
return MultiProvider(
providers: [
ChangeNotifierProvider<Posts>(
create: (context) => Posts(),
),
ChangeNotifierProvider<Settings>(
create: (context) => Settings(darkModeEnabled: true),
),
],
child: Consumer<Settings>(builder: (_, settings, child) {
return MaterialApp(
darkTheme:
settings.darkModeEnabled ? ThemeData.dark() : ThemeData.light(),
debugShowCheckedModeBanner: false,
title: 'Blogy',
theme: ThemeData(
primaryColor: Colors.deepPurple[900],
cursorColor: Colors.deepPurple[900],
accentColor: Colors.deepPurple[900],
fontFamily: 'Ubuntu',
),
home: SplashScreen(),
);
}),
);
full test code
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
class Posts extends ChangeNotifier {}
class Settings extends ChangeNotifier {
bool darkModeEnabled;
Settings({this.darkModeEnabled});
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<Posts>(
create: (context) => Posts(),
),
ChangeNotifierProvider<Settings>(
create: (context) => Settings(darkModeEnabled: true),
),
],
child: Consumer<Settings>(builder: (_, settings, child) {
return MaterialApp(
darkTheme:
settings.darkModeEnabled ? ThemeData.dark() : ThemeData.light(),
debugShowCheckedModeBanner: false,
title: 'Blogy',
theme: ThemeData(
primaryColor: Colors.deepPurple[900],
cursorColor: Colors.deepPurple[900],
accentColor: Colors.deepPurple[900],
fontFamily: 'Ubuntu',
),
home: SplashScreen(),
);
}),
);
}
}
class SplashScreen extends StatefulWidget {
SplashScreen({Key key}) : super(key: key);
//final String title;
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("test"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}