Flutter | Dark and Light theme using provider

pipaliya ashish
1 min readAug 17, 2020

ThemeChanger class extended by ChangeNotifier

class ThemeChanger extends ChangeNotifier {ThemeData _themeData;ThemeChanger(this._themeData);getTheme() => _themeData;setTheme(ThemeData theme) {_themeData = theme;notifyListeners();}}

wrap MaterialApp with ChangeNotifierProvider

return ChangeNotifierProvider<ThemeChanger>(create: (_) => ThemeChanger(lightTheme), child: MaterialAppParent());}

create instance of Provider<ThemeChanger>

final theme = Provider.of<ThemeChanger>(context);

create a toggle button to switch themes

theme.getTheme() == lightTheme? IconButton(icon: Icon(Icons.ac_unit),onPressed: () {theme.setTheme(darkTheme);}): IconButton(icon: Icon(Icons.lightbulb_outline),onPressed: () {theme.setTheme(lightTheme);})

--

--

pipaliya ashish

I write articles for my own reference only. I use medium.com as my digital notebook