Skip to content

Instantly share code, notes, and snippets.

@rodolfofranco
Created May 24, 2020 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodolfofranco/311a867cefbf62d2346ba4bd627543e0 to your computer and use it in GitHub Desktop.
Save rodolfofranco/311a867cefbf62d2346ba4bd627543e0 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
final darkTheme = ThemeData(
primarySwatch: Colors.grey,
primaryColor: Colors.black,
brightness: Brightness.dark,
backgroundColor: const Color(0xFF212121),
accentColor: Colors.white,
accentIconTheme: IconThemeData(color: Colors.black),
dividerColor: Colors.black12,
);
final lightTheme = ThemeData(
primarySwatch: Colors.grey,
primaryColor: Colors.white,
brightness: Brightness.light,
backgroundColor: const Color(0xFFE5E5E5),
accentColor: Colors.black,
accentIconTheme: IconThemeData(color: Colors.white),
dividerColor: Colors.white54,
);
class ThemeNotifier with ChangeNotifier {
ThemeData _themeData;
ThemeNotifier(this._themeData);
getTheme() => _themeData;
setTheme(ThemeData themeData) async {
_themeData = themeData;
notifyListeners();
}
}
void main() => runApp(ChangeNotifierProvider<ThemeNotifier>(
create: (_) => ThemeNotifier(lightTheme),
child: MyApp(),
));
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final themeNotifier = Provider.of<ThemeNotifier>(context);
return MaterialApp(
title: 'Dark Mode Example',
theme: themeNotifier.getTheme(),
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String mode = 'Light';
bool isDark = false;
@override
Widget build(BuildContext context) {
final themeNotifier = Provider.of<ThemeNotifier>(context);
return Scaffold(
body: Stack(
children: <Widget>[
Center(child: Text('Mode is: ' + mode)),
Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.all(40.0),
child: Switch(
value: isDark,
onChanged: (bool newVal) {
setState(() {
isDark = newVal;
});
if (isDark) {
mode = 'Dark';
themeNotifier.setTheme(darkTheme);
} else {
mode = 'Light';
themeNotifier.setTheme(lightTheme);
}
}),
))
],
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment