Change your app theme dynamically with GetX in Flutter

In this article, You will learn step by step how to get dynamic dark theme without any boilerplate code.

Motivation

This article consists of two parts

  • Part 1: How to get dynamic dark mode
  • Part 2: How to make the theme persistent

Also, there is an example project end of the article. You can check that out.

Part 1: How to get dynamic dark mode

Step 1: Add packages to your pubspec.yaml file

GetX is like a microframework that does almost everything for you. This time we will use it to change our app theme to the dark side.

Step 2: Create light and dark themes

In this case, we have only 2 themes.

Step 3: Change MaterialApp to GetMaterialApp and add the themes

GetX gives us more power and features to control MaterialApp, In order to use them we need to change the source of power

Step 4: Get your style from the theme

You can also use Theme.of(context) instead of context.theme

Step 5: Change the theme dynamically

if ThemeMode is dark mode then make it light else vice versa

That’s it! Your dynamic theme is ready to go! Now we can skip the next part. Let’s make the theme persistent

Part 2: How to make the theme persistent

Step 1: Add packages to your pubspec.yaml file

get_storage is a local storage package by GetX’s author. It’s an alternative of shared_preferences with better performance.

Step 2: Create ThemeService

Step 3: Init GetStorage and get ThemeMode from ThemeService

We initialize the local storage and get the theme info from the storage

Step 4: Add ThemeService().switchTheme to your button’s onPressed method

Example Project

If you’re the guy who better understands with source code. This is for you.

Thank you for Reading.

UI/UX Designer and Flutter developer