Change the theme of Flutter using Provider and Shared Preferences
--
In this article I will create a demo, to change app theme with provider
and shared_preferences
packages.
The way we change theme will differ according to the state management and local preference management packages that we have chosen for our app. This demo will help you if you are going with provider
package for state management. Here I have used theshared_preferences
package to persist my theme.
First let’s install the packages.
dependencies:
provider: ^latest_version
shared_preferences: ^latest_version
Now import like this.
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
I have used ChangeNotifierProvider for this demo. So in my main method I wrapped my Material class like this.
runApp(ChangeNotifierProvider<ThemeProvider>(
create: (BuildContext context) => ThemeProvider(),
child: const TravelApp()));
Then I can use ThemeProvider to change the theme and listen
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Travel App',
theme: Provider.of<ThemeProvider>(context).currentTheme
In my home screen app bar actions I have provided the change theme function as we do in a settings screen.
IconButton(
onPressed: () {
context.read<ThemeProvider>().changeCurrentTheme();
},
In order to do this, I need this currentTheme
variable and changeCurrentTheme
function in my ThemeProvider.
// this enum will help with the Theme type
enum ThemeType { light, dark }
class ThemeProvider extends ChangeNotifier {
ThemeData currentTheme = lightTheme;
ThemeType themeType = ThemeType.light;
changeCurrentTheme() {
if (currentTheme == darkTheme) {
themeType = ThemeType.light;
currentTheme = lightTheme;
} else {
themeType = ThemeType.dark;
currentTheme = darkTheme;
}
notifyListeners();
}
}
Now we have our provider to change the theme. I used the theme to change my theme changing action button like this. We can listen to the changes with…