Created
April 7, 2022 16:11
-
-
Save maheshj01/c81eccd13f45568ee10c4d160f1560c9 to your computer and use it in GitHub Desktop.
answering stackoverflow question https://stackoverflow.com/questions/49164592/flutter-how-to-change-the-materialapp-theme-at-runtime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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