Flutter: Implementing Dark Mode

Many great applications have gotten onboard the dark mode train because, we have to say it, everybody loves dark mode. It’s the perfect solution for when you need to view some content, or work without hurting your eyes at night. The best part is, wait for it… that improves battery life on most devices! It’s a win-win situation on every aspect.

In this article we are going to show you an easy way to implement dark mode using Flutter with the help of the provider package. First thing it’s to add the package to our pubspec.yaml file.

provider: ^4.1.2

Next, we need to create our sample app by using the flutter create command.

flutter create dark_theme_example

Now, we will create two themes inside our main.dart file —a light theme and a dark theme. We copy the following code at the beginning of our file.

import 'package:flutter/material.dart';

Next we add a ThemeNotifier, which will be in charge of handling theme’s changes in the application.

class ThemeNotifier with ChangeNotifier {

Now, the most important part is to wrap our application with a ChangeNotifierProvider making use of the provider package. Additionally, we need to use our ThemeNotifier inside our Material app, so the theme can be changed dynamically.

void main() => runApp(
ChangeNotifierProvider<ThemeNotifier>(
create: (_) => ThemeNotifier(lightTheme),
child: MyApp(),
));

Last step it’s to change the theme dynamically within our app, for this we are going to be using a Switch widget. We will be adding the following code to the MyHomePage widget.

Our final code should look like this:

If you followed all the steps correctly, you should end up with something like this.

Final App Result.

Hope you enjoyed this short guide on implementing dark mode. By using this solution, you will be implementing dark mode in your next application in no time!

Pushing your dreams into the internet.