Skip to content

Instantly share code, notes, and snippets.

@IsmailAlamKhan
Last active May 18, 2021 22:17
Show Gist options
  • Save IsmailAlamKhan/a596b1e602484c78d7d6b33161ec186f to your computer and use it in GitHub Desktop.
Save IsmailAlamKhan/a596b1e602484c78d7d6b33161ec186f to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({
Key? key,
}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final theme = CustomTheme();
@override
void initState() {
theme.addListener(() => setState(() {}));
super.initState();
}
@override
void dispose() {
theme.removeListener(() => setState(() {}));
super.dispose();
}
@override
Widget build(BuildContext context) {
return ThemeInheritedWidget(
theme: theme,
child: Builder(
builder: (context) {
final _theme = ThemeInheritedWidget.of(context)!.theme;
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
debugShowCheckedModeBanner: false,
themeMode: _theme.mode,
home: Home(),
);
},
),
);
}
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final _theme = ThemeInheritedWidget.of(context)!.theme;
return Scaffold(
appBar: AppBar(
backgroundColor: _theme.myTheme.appBarColor,
actions: [
Switch.adaptive(
value: _theme.darkMode,
onChanged: (val) {
if (!val) {
_theme.mode = ThemeMode.light;
} else {
_theme.mode = ThemeMode.dark;
}
},
),
],
),
backgroundColor: _theme.myTheme.backgroundColor,
);
}
}
class ThemeInheritedWidget extends InheritedWidget {
ThemeInheritedWidget({
Key? key,
required this.child,
required this.theme,
}) : super(key: key, child: child);
final Widget child;
final CustomTheme theme;
static ThemeInheritedWidget? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<ThemeInheritedWidget>();
}
@override
bool updateShouldNotify(ThemeInheritedWidget oldWidget) =>
oldWidget.theme.mode != theme.mode;
}
class CustomTheme extends ChangeNotifier {
ThemeMode _mode = ThemeMode.system;
ThemeMode get mode => _mode;
bool get darkMode => mode == ThemeMode.dark;
set mode(ThemeMode mode) {
if (mode == _mode) return null;
_mode = mode;
notifyListeners();
}
MyTheme get myTheme => darkMode ? MyTheme.dark() : MyTheme.light();
}
///TODO ADD Many properties to this class as you wish
class MyTheme {
final Color backgroundColor;
final Color appBarColor;
MyTheme({required this.backgroundColor, required this.appBarColor});
MyTheme.light()
: backgroundColor = Colors.red,
appBarColor = Colors.amber;
MyTheme.dark()
: backgroundColor = Colors.blueGrey,
appBarColor = Colors.indigo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment