///////////////flutter dark/light theme with provider example
/************ main.dart ******************/
// add to pubspec.yaml - provider: ^4.0.5
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './theme_model.dart';
void main() => runApp(MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => ThemeModel(),
),
],
child: MyApp(),
));
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext bc) {
return Consumer(
builder: (BuildContext bc, ThemeModel themeModel, Widget w){
return MaterialApp(
title: 'title',
theme: themeModel.currentTheme,
home: Home(title:'title'),
);});}}
class Home extends StatelessWidget{
final String title;
Home({this.title});
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child:RaisedButton(child: Text("Change Theme"),
onPressed:() => Provider.of(context, listen:false).toggleTheme(),
),));}}
/***************** theme_model.dart ****************/
import 'package:flutter/material.dart';
import './theme.dart';
enum ThemeType { Light, Dark }
class ThemeModel extends ChangeNotifier {
ThemeData currentTheme = darkTheme;
ThemeType _themeType = ThemeType.Dark;
toggleTheme() {
if (_themeType == ThemeType.Dark) {
currentTheme = lightTheme;
_themeType = ThemeType.Light;
return notifyListeners();
}
if (_themeType == ThemeType.Light) {
currentTheme = darkTheme;
_themeType = ThemeType.Dark;
return notifyListeners();
}}}
/******************** theme.dart ******************/
import 'package:flutter/material.dart';
ThemeData darkTheme = ThemeData.dark().copyWith(
primaryColor: Color(0xff1f655d),
accentColor: Color(0xff40bf7a),
textTheme: TextTheme(
title: TextStyle(color: Color(0xff40bf7a)),
subtitle: TextStyle(color: Colors.white),
subhead: TextStyle(color: Color(0xff40bf7a))),
appBarTheme: AppBarTheme(color: Color(0xff1f655d)));
ThemeData lightTheme = ThemeData.light().copyWith(
primaryColor: Color(0xfff5f5f5),
accentColor: Color(0xff40bf7a),
textTheme: TextTheme(
title: TextStyle(color: Colors.black54),
subtitle: TextStyle(color: Colors.grey),
subhead: TextStyle(color: Colors.white)),
appBarTheme: AppBarTheme(
color: Color(0xff1f655d),
actionsIconTheme: IconThemeData(color: Colors.white)));