Created
June 3, 2023 06:45
-
-
Save yousefak007/f453445deb7c8886b8ddcdae1205ebee to your computer and use it in GitHub Desktop.
Using Toggle theme from System to light or System to dark with Consumer
This file contains 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'; | |
import 'package:provider/provider.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return ChangeNotifierProvider<Settings>( | |
create: (context) => Settings(), | |
child: Consumer<Settings>(builder: (context, appSettings, _) { | |
return AnimatedBuilder( | |
animation: appSettings, | |
builder: (context, snapshot) { | |
return MaterialApp( | |
theme: ThemeData.light(), | |
darkTheme: ThemeData.dark(), | |
themeMode: appSettings.theme, | |
home: const 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: Consumer<Settings>(builder: (context, appSettings, _) { | |
return Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
ToggleButtons( | |
children: const [ | |
Text('Light'), | |
Text('Dark'), | |
Text('System'), | |
], | |
constraints: | |
const BoxConstraints(minWidth: 80, minHeight: 40), | |
onPressed: (int index) { | |
print(index); | |
ThemeMode theme = ThemeMode.light; | |
switch (index) { | |
case 0: | |
theme = ThemeMode.light; | |
break; | |
case 1: | |
theme = ThemeMode.dark; | |
break; | |
case 2: | |
theme = ThemeMode.system; | |
break; | |
} | |
appSettings.theme = theme; | |
}, | |
isSelected: [ | |
appSettings.theme == ThemeMode.light, | |
appSettings.theme == ThemeMode.dark, | |
appSettings.theme == ThemeMode.system, | |
]), | |
Text( | |
appSettings.theme == ThemeMode.dark ? 'Dark' : 'Light', | |
style: Theme.of(context).textTheme.headlineMedium, | |
), | |
], | |
); | |
}), | |
), | |
); | |
} | |
} | |
class Settings extends ChangeNotifier { | |
ThemeMode _theme = ThemeMode.light; | |
ThemeMode get theme => _theme; | |
set theme(ThemeMode theme) { | |
_theme = theme; | |
notifyListeners(); | |
} | |
@override | |
void notifyListeners() { | |
super.notifyListeners(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment