Flutter- Dark/light theme using Provider

ravinder ganwal
1 min readJul 10, 2021

Dark and light theme is a important feature now a days, and specially the dark themes are becoming more and more popular. I have created a repo for completed code here.

So lets start how to give dark support in flutter app using provider package,

firstly add provider and get_it in your pubspec.yaml,

dependencies:
flutter:
sdk: flutter


# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
provider: ^5.0.0
get_it: ^7.1.3

Then declare a class which extends ChangeNotifier class, which has a boolean flag isDarkMode, which will notify the app whenever its state changes,

import 'package:flutter/material.dart';

class AppTheme with ChangeNotifier {
bool isDarkMode = false;
getDarkMode() => this.isDarkMode;
void changeDarkMode(isDarkMode) {
this.isDarkMode = isDarkMode;
notifyListeners();//notify the view about the boolean state
}
}

Then apply theme like this,

@override
Widget build(BuildContext context) {
final appTheme = Provider.of<AppTheme>(context);
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: appTheme.getDarkMode() ? ThemeData.dark() : ThemeData.light(),
title: 'Flutter Demo',
home: Home(),
);
}

How to change theme?

IconButton(
onPressed: () {
if (appTheme.isDarkMode)
appTheme.changeDarkMode(false);
else
appTheme.changeDarkMode(true);
},
icon: Icon(
appTheme.isDarkMode ? Icons.light_mode : Icons.dark_mode))

Please find complete code here,

https://github.com/raviganwal/change_theme_using_provider.git

--

--