Hello, my Flutter buddy! Ever feel like your app’s theme is a bit like wearing the same outfit every day? Sometimes, you just need a change! Whether you want your app to rock the dark side or shine bright with a light theme, we’ve got you covered.
Today, we’re discussing dynamic theme switching using the mighty provider package in Flutter. Ready to give your app a makeover? Let’s jump right in!
Table of Contents
The Age-Old Problem: Theme Switching
Let’s face it, we’ve all been there. You build this fantastic app, only to realize that switching between light and dark themes feels like trying to solve a Rubik’s cube blindfolded.
You know it’s possible, but it’s a real head-scratcher. Fear not! With Provider, theme switching is smoother than a cat’s purr.
Setting the Scene: The Basics of Provider
Before we dive into theme switching, let’s get a quick refresher on Provider. Think of Proivder as your trusty sidekick that manages the state of your app with the grace of a ballet dancer. Whether it’s managing a simple counter or a complex theme switcher, Provider makes your life easier.
I already posted an article about the basics of providers on my website. Just check it out and enjoy!
Adding Provider to your project
First, let’s add the Provider package to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
provider: ^6.0.0
The Grand Plan: Dynamic Theme Switching
Here’s our game plan:
- Create a theme provider: This will hold our theme data and switch logic.
- Set Up Provider: Integrate Provider into our app.
- Build the UI: Create a simple UI to switch themes.
Introducing the ThemeProvider
Meet ThemeProvider,
your new best friend for managing app themes. This trusty sidekick keeps track of whether your app is in light or dark mode and makes switching between them as easy as pie.
Your Code: The Hero We Deserve
Let’s take a look at your awesome implementation of ThemeProvider
and how it fits into our Flutter app.
theme_provider.dart
Here’s the code for ThemeProvider
that handles the theme logic:
import 'package:flutter/material.dart';
class ThemeProvider extends ChangeNotifier {
bool _isDark = false;
bool get isDark => _isDark;
ThemeData get currentTheme => _isDark ? ThemeData.dark() : ThemeData.light();
void toggleTheme() {
_isDark = !_isDark;
notifyListeners();
}
}
This little gem toggles between light and dark themes and notifies listeners whenever the theme changes. Simple yet powerful!
Setting Up Provider
Now, let’s integrate ThemeProvider
into our app. We use MultiProvider
to manage multiple providers easily.
main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_tutorial/counter_screen.dart';
import 'package:provider_tutorial/provider/theme_provider.dart';
import 'provider/counter_provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => CounterProvider()),
ChangeNotifierProvider(create: (context) => ThemeProvider())
],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
final ThemeProvider themeProvider = Provider.of(context);
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Provider Tutorial',
theme: themeProvider.currentTheme,
home: const CounterScreen(),
);
}
}
We wrap our app with MultiProvider
and pass instances of CounterProvider
and ThemeProvider
. The current theme is applied using themeProvider.currentTheme
.
Building the Theme Switcher UI
Finally, let’s create a user interface that allows users to switch themes with the press of a button.
change_theme.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_tutorial/provider/theme_provider.dart';
class ChangeTheme extends StatelessWidget {
const ChangeTheme({super.key});
@override
Widget build(BuildContext context) {
final ThemeProvider themeProvider = Provider.of(context, listen: false);
return Scaffold(
appBar: AppBar(
title: const Text('Change Theme'),
centerTitle: true,
),
body: Consumer(
builder: (context, value, child) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
themeProvider.isDark ? "I AM DARK MODE" : "I AM LIGHT MODE",
style: const TextStyle(
fontSize: 30, fontWeight: FontWeight.bold),
),
const SizedBox(height: 20),
const Text("Change your theme by clicking the button"),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
themeProvider.toggleTheme();
},
child: themeProvider.isDark
? const Text("Change theme to Light mode")
: const Text('Change theme to dark mode'),
)
],
),
);
},
),
);
}
}
Our ChangeTheme
widget uses Consumer
to listen to theme changes and update the UI accordingly. The button toggles between light and dark modes with a simple press, making theme switching feel like flipping a light switch!
Check out the full code on Github.
Output:
Make Your App Shine!
And there you have it, folks! You’ve just learned how to dynamically change your app’s theme using the power of Provider
. Now, your app can switch between light and dark modes with the grace of a ninja and the simplicity of a single button press. So go ahead, give your users the power to choose their theme, and watch as your app becomes the coolest kid on the block.
Remember, with great power comes great responsibility. Use this theme-switching magic wisely, and keep your users dazzled. Until next time, happy coding, and may your apps be ever dynamic and stylish!