DEV Community

DhiWise
DhiWise

Posted on • Edited on

12

Dark theme using GetX

[Source: Mighty Techno](https://mightytechno.com/category/app-development/flutter-app-development/)

Adding a Light and Dark theme for your app kind of becomes a mandatory thing in today’s app world. Because most people prefer a dark theme over a light theme because it is pretty comfortable for our eyes and reduces battery consumption.

For implementing a dynamic theme we are going to use a well-known flutter framework named GetX.

The simplest way of changing the light to dark is by changing the theme of the MaterialApp widget to light to dark. For that, we need two themes like dark and light.

What is GetX?

GetX is an extra-light and powerful solution for Flutter. It combines high-performance state management, intelligent dependency injection, and route management quickly and practically

Installing GetX and shared preference:

Add these two dependencies in your project’s pubspec.yaml file.

get: any
shared_preferences: any
Enter fullscreen mode Exit fullscreen mode

Shared Preferences will be used to save the theme, so whenever you return to the app you will get the theme that you selected previously.

Let’s start implementing it…

Define light and dark theme data (like the accent color, primary and secondary color, etc.)

ThemeData _darkTheme = ThemeData(
    accentColor: Colors.red,
    brightness: Brightness.dark,
    primaryColor: Colors.amber,
    buttonTheme: ButtonThemeData(
      buttonColor: Colors.amber,
      disabledColor: Colors.grey,
    ));

ThemeData _lightTheme = ThemeData(
    accentColor: Colors.pink,
    brightness: Brightness.light,
    primaryColor: Colors.blue,
    buttonTheme: ButtonThemeData(
      buttonColor: Colors.blue,
      disabledColor: Colors.grey,
    ))
Enter fullscreen mode Exit fullscreen mode

Now add one variable to manage the theming of your app.

We are adding a RxBool _isLightTheme = false.obs For that.

Now add following theme property like this in your GetMaterialApp Widget:

theme: _lightTheme,
darkTheme: _darkTheme,
themeMode: ThemeMode.system,
Enter fullscreen mode Exit fullscreen mode

[Source : Dribble](https://dribbble.com/shots/2407427-Light-Switch-animation)

Now we are going to use Switch to manage the dark and light themes. Here is an example of adding a switch widget on your screen.

ObxValue(
  (data) => Switch(
     value: _isLightTheme.value,
     onChanged: (val) {
       _isLightTheme.value = val;
       Get.changeThemeMode(
          _isLightTheme.value ? ThemeMode.light : ThemeMode.dark,
        );
        _saveThemeStatus();
      },
    ),
    false.obs,
 ),
Enter fullscreen mode Exit fullscreen mode

Wanna make it persistent?

If Yes, Let’s Do it… The following steps will help you to keep the selected theme persistently.

First of all, create an instance or shared preference and add two methods for getting the value of the theme and setting the value of the theme.

Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  _saveThemeStatus() async {
    SharedPreferences pref = await _prefs;
    pref.setBool('theme', _isLightTheme.value);
  }

  _getThemeStatus() async {
    var _isLight = _prefs.then((SharedPreferences prefs) {
      return prefs.getBool('theme') != null ? prefs.getBool('theme') : true;
    }).obs;
    _isLightTheme.value = await _isLight.value;
    Get.changeThemeMode(_isLightTheme.value ? ThemeMode.light : ThemeMode.dark);
Enter fullscreen mode Exit fullscreen mode

Now to initialize the selected theme in your app call the getThemeStatus() method at the start of your app by using the initState() method.

@override
  void initState() {
    super.initState();
    _getThemeStatus();
  }
Enter fullscreen mode Exit fullscreen mode

Here is an complete main.dart file for the reference:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
ThemeData _darkTheme = ThemeData(
accentColor: Colors.red,
brightness: Brightness.dark,
primaryColor: Colors.amber,
buttonTheme: ButtonThemeData(
buttonColor: Colors.amber,
disabledColor: Colors.grey,
));
ThemeData _lightTheme = ThemeData(
accentColor: Colors.pink,
brightness: Brightness.light,
primaryColor: Colors.blue,
buttonTheme: ButtonThemeData(
buttonColor: Colors.blue,
disabledColor: Colors.grey,
));
class MyApp extends StatelessWidget {
RxBool _isLightTheme = false.obs;
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
_saveThemeStatus() async {
SharedPreferences pref = await _prefs;
pref.setBool('theme', _isLightTheme.value);
}
_getThemeStatus() async {
var _isLight = _prefs.then((SharedPreferences prefs) {
return prefs.getBool('theme') != null ? prefs.getBool('theme') : true;
}).obs;
_isLightTheme.value = await _isLight.value;
Get.changeThemeMode(_isLightTheme.value ? ThemeMode.light : ThemeMode.dark);
}
MyApp() {
_getThemeStatus();
}
@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: _lightTheme,
darkTheme: _darkTheme,
themeMode: ThemeMode.system,
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('Dark Mode Demo'),
),
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Obx(
() => Text(
'Click on switch to change to ${_isLightTheme.value ? 'Dark' : 'Light'} theme',
),
),
ObxValue(
(data) => Switch(
value: _isLightTheme.value,
onChanged: (val) {
_isLightTheme.value = val;
Get.changeThemeMode(
_isLightTheme.value ? ThemeMode.light : ThemeMode.dark,
);
_saveThemeStatus();
},
),
false.obs,
),
],
),
),
),
),
);
}
}
view raw main.dart hosted with ❤ by GitHub

Conclusion:

Let’s Wrap It. There are many ways for implementing dynamic theming in flutter since GetX is a more efficient way to implement it. Hope you liked this content. If you found it useful then share it with your development team.

Thanks for reading this article ❤

If I got something wrong 🙈, Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

References:

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or leave a kind comment!

Okay