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.
In case you prefer tutorial videos over written tutorials, check out this YouTube video:
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
P and enter
Flutter: New Project. Alternatively, you can click on
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
darkTheme. Add the following code inside the
So what has changed? We just added a new property to
darkTheme which takes
ThemeData as an argument. You can specify theme data for the dark theme in two ways:
brightness: Brightness.darkto specify that it corresponds to dark theme.
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 be
Colors.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
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?
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
MaterialApp class documentation: https://api.flutter.dev/flutter/material/MaterialApp-class.html
darkTheme property documentation: https://api.flutter.dev/flutter/material/MaterialApp/darkTheme.html
ThemeData.dark constructor documentation: https://api.flutter.dev/flutter/material/ThemeData/ThemeData.dark.html