Control the theme of your app like a pro — Flutter💙

We can change the theme from light to dark or vice-versa easily using package or State Management techniques. But let’s see how you can do this without using a single package!

Bored of reading? Feel free to clone the repository from GitHub!

Step 1: Change MyApp to Stateful Widget

import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Home(),
);
}
}

Step 2: Create a ThemeMode variable inside _MyAppState and provide the initial theme!

class _MyAppState extends State<MyApp> {
ThemeMode _themeMode = ThemeMode.light;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
themeMode: _themeMode,
theme: ThemeData(),
darkTheme: ThemeData.dark(),
home: Home(),
);
}
}

Step 3: Create a static function inside MyApp.

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
static _MyAppState? of(BuildContext context) => context.findAncestorStateOfType<_MyAppState>();
}

Step 4: Create a function to change the theme in _MyAppState

void changeTheme(ThemeMode themeMode) {
setState(() {
_themeMode = themeMode;
});
}

Step 5: Let’s create our home.dart which will have a switch in the centre!

import 'package:flutter/material.dart';
import 'package:theme_example/main.dart';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool _value = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Switch(
value: _value,
onChanged: (value) {},
),
),
);
}
}

Step 6: Call changeTheme function (created in _MyAppState) using the static function (created in MyApp)

setState(() {
_value = value;
if (_value)
MyApp.of(context)!.changeTheme(ThemeMode.dark);
else
MyApp.of(context)!.changeTheme(ThemeMode.light);
});

Output:

Hope you enjoyed this article!

Don’t forget to connect with me on:

Don’t stop, until you are breathing!💙
- Abhishek Doshi

Google Developer Expert — Dart & Flutter 💙