Flutterexperts

Crafting Next-Gen Apps with Flutter Power
Change Dynamically Theme In Flutter

As you probably are aware, Flutter as of late dropped its significant adaptation update, for example, Flutter 3.0. It brings a ton of changes, and I was hanging tight for such a long time, Material You, which was formally divulged at Google IO 2021. Look at this link for the individuals who don’t have the foggiest idea of what Material You are.

In this article, we will explore the Change Dynamically Theme In Flutter. We will see how to implement a demo program. How to get dynamic dark/light mode using the get package and how to make the theme persistent using the get_storage package in your flutter applications.

For GetX:

get | Flutter Package
GetX is an extra-light and powerful solution for Flutter. It combines high-performance state management, and intelligent…pub.dev

For Get Storage:

get_storage | Flutter Package
A fast, extra light, and synchronous key-value in memory, which backs up data to disk at each operation. It is written…pub.dev

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

It’s extraordinary assistance for overseeing themes in Flutter, however, to make it work appropriately we’ll have to ensure we’ve populated the theme and darkTheme properties on MaterialApp with the elegantly thought out and masterfully variety composed themes that our UI/UX group has made. We will change MaterialApp to GetMaterialApp utilizing getx.

ThemeMode grants us the following states:

  • Themes.light— We will create a new Themes() class and add ThemeData.light() with background color, button color, etc. Apply the theme referenced by the theme property on GetMaterialApp. Of course, this theme should have its brightness set to be a copyWith from the Flutter supplied ThemeData.light().
  • Themes.dark— Apply the theme referenced by the darkTheme property on GetMaterialApp. Again, this theme should have its brightness set to be a copyWith from the Flutter supplied ThemeData.dark().
  • ThemeService().theme — We will create a new ThemeService() class using GetStorage and apply the theme referenced by the themeMode property on GetMaterialAppthat matches the mode currently in use on the device. Now this one is interesting as it will set the theme of our app to match the modes of the device when our app starts, and it will dynamically change our app’s theme to track the mode on the device when it changes between light and dark.

Demo Module ::

This demo video shows how to change the dynamic theme in a flutter and shows how a dynamic theme will work using the get package and how to make the theme persistent using the get_storage package in your flutter applications. We will show a user press the button then the theme will be changed into the light mode to dark mode/vice versa and also the theme was persistent. It will be shown on your device.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
get:
get_storage:

Step 2: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/

Step 3: Import

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

Step 4: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called app_theme.dart inside the lib folder.

In the app_theme file inside, we will create a Themes class. In this class, we will add two static methods first one is light and the other is dark. Both have ThemeData.light()/dark(). copy with background color, button color, etc.

import 'package:flutter/material.dart';

class Themes {
static final light = ThemeData.light().copyWith(
backgroundColor: Colors.white,
buttonColor: Colors.cyan,
bottomAppBarColor: Colors.cyan,
buttonTheme: const ButtonThemeData(
buttonColor: Colors.cyan,
textTheme: ButtonTextTheme.primary,
),
);
static final dark = ThemeData.dark().copyWith(
backgroundColor: Colors.black,
buttonColor: Colors.deepPurple,
bottomAppBarColor: Colors.deepPurple,
buttonTheme: const ButtonThemeData(
buttonColor: Colors.deepPurple,
textTheme: ButtonTextTheme.primary,
),
);
}

Create a new dart file called main.dart inside the lib folder.

In the main. dart file, we will return a GetMaterialApp(). Inside, we will add a theme that is equal to the Themes. light(we will already define above) and a darkTheme that is equal to the Themes. light

@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: Themes.light,
darkTheme: Themes.dark,
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

Same dart file, we will create a MyHomePage() new class. In this class, we will get your style from the theme. You can also use Theme.of(context) it instead of context.theme

return Scaffold(
backgroundColor: context.theme.backgroundColor,
.....
)

In the body, we will create an ElevatedButton. In this button, we will add a primary, padding, textStyle, and onPressed method. In this method, we will add if Get.isDarkMode then our theme Get.changeThemeMode(ThemeMode.light) else Get.changeThemeMode(ThemeMode.dark). Its child, we will add the text ‘Change Theme’. Your dynamic theme is ready to go!.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: context.theme.buttonColor,
padding:
const EdgeInsets.symmetric(horizontal: 30, vertical: 16),
textStyle: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
onPressed:
() {
if (Get.isDarkMode) {
Get.changeThemeMode(ThemeMode.light);
} else {
Get.changeThemeMode(ThemeMode.dark);
}
},
child: const Text('Change Theme')),

Let’s make the theme persistent:

Create a new dart file called theme_service.dart inside the lib folder.

get_storage is a local storage package by GetX’s author. It’s an alternative to shared_preferences with better performance. We will create a ThemeService class.

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class ThemeService {
final _box = GetStorage();
final _key = 'isThemeMode';

ThemeMode get theme => _loadThemeFromBox() ? ThemeMode.dark : ThemeMode.light;

bool _loadThemeFromBox() => _box.read(_key) ?? false;
_saveThemeToBox(bool isDarkMode) => _box.write(_key, isDarkMode);

void switchTheme() {
Get.changeThemeMode(_loadThemeFromBox() ? ThemeMode.light : ThemeMode.dark);
_saveThemeToBox(!_loadThemeFromBox());
}
}

Now, we will initialize the local storage and get the theme info from the storage in main.dart file.

void main() async{
await GetStorage.init();
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: Themes.light,
darkTheme: Themes.dark,
themeMode: ThemeService().theme,
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

Final, we will add ThemeService().switchTheme to your button’s onPressed method on a ElevatedButton in MyHomePage() class.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: context.theme.buttonColor,
padding:
const EdgeInsets.symmetric(horizontal: 30, vertical: 16),
textStyle: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
onPressed:ThemeService().switchTheme,
child: const Text('Change Theme')),

The user can run the application on devices then, and the theme will be persistent and work perfectly Fine.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_dynamically_theme/app_theme.dart';
import 'package:flutter_dynamically_theme/splash_screen.dart';
import 'package:flutter_dynamically_theme/theme_service.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

void main() async{
await GetStorage.init();
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: Themes.light,
darkTheme: Themes.dark,
themeMode: ThemeService().theme,
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: context.theme.backgroundColor,
appBar: AppBar(
backgroundColor: context.theme.bottomAppBarColor,
title: const Text("Flutter Change Dynamically Theme Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/logo.png',
height: 300,
width: 350,
),
const SizedBox(height: 80,),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: context.theme.buttonColor,
padding:
const EdgeInsets.symmetric(horizontal: 30, vertical: 16),
textStyle: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
onPressed:ThemeService().switchTheme,
child: const Text('Change Theme')),
],
),
),
);
}
}

Conclusion:

In the article, I have explained the Change Dynamically Theme in a flutter; you can modify this code according to your choice. This was a small introduction to Dynamically Theme On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying up the Change Dynamically Theme in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working on Change Dynamically Theme using the get package and also make the theme persistent using the get_storage package in your flutter applications. So please try it.

❤ ❤ 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.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.