Change Flutter app theme based on device settings
Nowadays, almost every app has an option to change its theme. Usually, these apps have three theme options: light, dark and system default. In this article, we will be focusing on the third option, i.e. system default.
YouTube tutorial:
In case you prefer tutorial videos over written tutorials, check out this YouTube video:
Coming soon…
Let’s begin!
Let’s start off by creating a new Flutter app, called auto_theme_app
. I am using VS Code for this tutorial, but you can use any other IDE (like Android Studio) or even the terminal.
To create a new Flutter project in VS Code, press Ctrl
+ Shift
+ P
and enter Flutter: New Project
. Alternatively, you can click on View
, then Command Pallette…
.
We will name the app auto_theme_app
as the app will automatically change its theme based on the device theme settings.
Once the Flutter project is created, open the main.dart
file. Remove all the comments so that the code looks a bit cleaner. Alternatively, you can clear the entire file and paste the following code:
When we run this app, we can only see the light theme. To add a dark theme to this app, we will use a property of MaterialApp
called darkTheme
. Add the following code inside the MaterialApp()
:
So what has changed? We just added a new property to MaterialApp
called darkTheme
which takes ThemeData
as an argument. You can specify theme data for the dark theme in two ways:
- Using
brightness
property ofThemeData
:
InThemeData()
, addbrightness: Brightness.dark
to specify that it corresponds to dark theme. - Using
ThemeData.dark()
:
This gives a default dark theme with a teal accent color.
So which one of these should we use?
I prefer to use the first one as it gives me more control over the theme. For example, if you want the primary color of the application to beColors.purple
and the accent color to Colors.purpleAccent
, you can do so by adding the following code to the ThemeData
corresponding to the dark theme:
However, you cannot do that if you use ThemeData.dark()
.
That’s it!
Yeah, it was as simple as adding a darkTheme
property to the MaterialApp()
! Now test out your app by changing the theme of your device inside the system settings. Your app should automatically switch between light and dark theme when you change the device’s theme. Honestly, I prefer dark theme where ever I can find it. Which theme do you prefer?
Resources:
Here’s a list of a few resources which may be useful for you:
1. Source code of the app we created above: https://github.com/masteradit/Flutter-Tutorials/tree/01-auto-theme-app
2. MaterialApp
class documentation: https://api.flutter.dev/flutter/material/MaterialApp-class.html
3. darkTheme
property documentation: https://api.flutter.dev/flutter/material/MaterialApp/darkTheme.html
4.ThemeData.dark
constructor documentation: https://api.flutter.dev/flutter/material/ThemeData/ThemeData.dark.html