Skip to content

Instantly share code, notes, and snippets.

@maheshmnj
Created April 7, 2022 16:11
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 maheshmnj/c81eccd13f45568ee10c4d160f1560c9 to your computer and use it in GitHub Desktop.
Save maheshmnj/c81eccd13f45568ee10c4d160f1560c9 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
Settings appSettings = Settings();
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: appSettings,
builder: (context, snapshot) {
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: appSettings.getTheme,
home: MyAwesomeApp(title: "Dark Theme Sample"),
);
});
}
}
class MyAwesomeApp extends StatefulWidget {
const MyAwesomeApp({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyAwesomeApp> createState() => _MyAwesomeAppState();
}
class _MyAwesomeAppState extends State<MyAwesomeApp> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Drag the button to change the Theme',
),
Switch(
value: appSettings.getTheme == ThemeMode.dark,
onChanged: (isDark) {
if (isDark) {
appSettings.setTheme(ThemeMode.dark);
} else {
appSettings.setTheme(ThemeMode.light);
}
}),
Text(
appSettings.getTheme == ThemeMode.dark ? 'Dark' : 'Light',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
);
}
}
class Settings extends ChangeNotifier {
ThemeMode theme = ThemeMode.light;
ThemeMode get getTheme => theme;
void setTheme(ThemeMode theme) {
this.theme = theme;
notifyListeners();
}
void notifyListeners() {
super.notifyListeners();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment