On this page16 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. The Problem With Passing Callbacks
- 2. Adding Provider
- 3. A ChangeNotifier: State Plus a Bell
- 4. ChangeNotifierProvider: Put It Above the App
- 5. Reading It: Provider.of
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Key Takeaways
- Full Code (Copy-Paste Reference)
Lecture 004: Why Provider? A ThemeProvider With ChangeNotifier
| Category | 2: Provider |
| Lecture | 004 of 008 |
| Estimated video length | 14 min |
| Target | Flutter 3.44 · Dart 3.12 · provider 6.1 |
| Level | Beginner |
In Lecture 003 the theme switch worked because the button was on the screen right below
MaterialApp. Put it on a Settings screen three pages deep, and passing callbacks down every level becomes a mess. Provider puts the theme in one place that any screen can read and change.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lecture 003, plus Dart classes, getters and private fields (Dart Basic 030–035).
Connection With Previous Lectures
The _themeMode state and _setDark method that lived in _NotesAppState move into their own
class, ThemeProvider. NotesApp goes back to being a simple StatelessWidget.
Learning Objectives
- Explain why passing callbacks down many screens doesn't scale
- Add the
providerpackage - Write a
ThemeProviderthat extendsChangeNotifierand callsnotifyListeners() - Put it above the app with
ChangeNotifierProvider - Read it with
Provider.of, with and withoutlisten: false
1. The Problem With Passing Callbacks
NotesApp (owns themeMode)
└─ HomeScreen (needs onDarkChanged only to pass it on)
└─ SettingsScreen (needs onDarkChanged only to pass it on)
└─ ThemeSwitch (actually uses it)Every screen in between has to accept and forward a callback it doesn't care about. This is called prop drilling, and it gets worse with every new setting.
2. Adding Provider
flutter pub add providerThis adds provider: ^6.1.5+1 (or newer) to pubspec.yaml. Then import it where needed:
import 'package:provider/provider.dart';3. A ChangeNotifier: State Plus a Bell
ChangeNotifier is a Flutter class with one superpower: notifyListeners(). Call it after
changing data, and every widget listening to it rebuilds.
lib/theme_provider.dart
import 'package:flutter/material.dart';
class ThemeProvider extends ChangeNotifier {
ThemeMode _themeMode = ThemeMode.light;
ThemeMode get themeMode => _themeMode;
bool get isDark => _themeMode == ThemeMode.dark;
void toggle() {
_themeMode = isDark ? ThemeMode.light : ThemeMode.dark;
notifyListeners();
}
}- The field is private (
_themeMode), so it can only change throughtoggle(). toggle()changes the data, then rings the bell withnotifyListeners().
We start in ThemeMode.light here so toggle() always flips something visible (remember the
"system" trap from Lecture 003). System mode comes back in Lecture 008.
4. ChangeNotifierProvider: Put It Above the App
Wrap the app so every widget below can reach the provider:
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => ThemeProvider(),
child: const NotesApp(),
),
);
}create makes the ThemeProvider once and keeps it alive for the whole app.
5. Reading It: Provider.of
// Rebuilds this widget whenever the provider notifies:
final themeProvider = Provider.of<ThemeProvider>(context);
// Just grabs it once, without listening (for button handlers):
Provider.of<ThemeProvider>(context, listen: false).toggle();| Call | Rebuilds on change? | Use it… |
|---|---|---|
Provider.of<T>(context) | yes | in build, to show data |
Provider.of<T>(context, listen: false) | no | in onPressed and other callbacks |
Lecture 005 shows shorter ways to write both.
Code Examples
Example 1: My Notes With a ThemeProvider
lib/theme_provider.dart: as in Section 3.
lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'theme_provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => ThemeProvider(),
child: const NotesApp(),
),
);
}
class NotesApp extends StatelessWidget {
const NotesApp({super.key});
@override
Widget build(BuildContext context) {
final themeProvider = Provider.of<ThemeProvider>(context);
return MaterialApp(
title: 'My Notes',
debugShowCheckedModeBanner: false,
theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal)),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.teal,
brightness: Brightness.dark,
),
),
themeMode: themeProvider.themeMode,
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('My Notes'),
actions: [
IconButton(
tooltip: 'Toggle theme',
icon: const Icon(Icons.brightness_6),
onPressed: () {
Provider.of<ThemeProvider>(context, listen: false).toggle();
},
),
],
),
body: const Center(child: Text('Buy milk and bread')),
);
}
}What happens when you tap the button:
toggle()changes_themeModeand callsnotifyListeners().NotesAppis listening (Provider.ofwithoutlisten: false), so it rebuilds.MaterialAppgets the newthemeMode, and the whole app switches.
HomeScreen no longer needs any callback parameter. Any screen, however deep, can do the same.
Common Beginner Mistakes
1. Forgetting notifyListeners()
void toggle() {
_themeMode = isDark ? ThemeMode.light : ThemeMode.dark; // no notifyListeners()
}No error, but nothing happens on screen. The data changed, but nobody was told. (We tested it: the field changed, the screen didn't.)
2. No provider above the widget
Error: Could not find the correct Provider<ThemeProvider> above this Builder WidgetChangeNotifierProvider must wrap the widgets that read it. Put it in main(), around the whole
app.
3. Listening inside a button handler
onPressed: () => Provider.of<ThemeProvider>(context).toggle(),Tapping it fails with:
Tried to listen to a value exposed with provider, from outside of the widget tree.
This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.Add listen: false in callbacks.
Best Practices
- One provider class per topic (
ThemeProvider, later maybeCartProvider). - Keep fields private and change them only through methods that call
notifyListeners(). - Put app-wide providers in
main(), aboveMaterialApp.
Mini Challenge
Add a Text to HomeScreen's body that shows Dark mode: true/false using
Provider.of<ThemeProvider>(context).isDark. Tap the button and check it updates.
Practice Questions
- What is "prop drilling"?
- What does
notifyListeners()do? - Where should
ChangeNotifierProvidergo for an app-wide setting? - When do you pass
listen: false? - What happens if you forget
notifyListeners()?
Practice Answers
- Passing data or callbacks down through widgets that don't use them, just to reach a deeper widget.
- It tells every listening widget to rebuild.
- In
main(), wrapping the whole app. - In event handlers like
onPressed, where you only want to call a method, not rebuild. - The data changes but the screen doesn't update.
Key Takeaways
- Provider shares state with any widget below it, without passing callbacks around.
- A
ChangeNotifierholds the state and callsnotifyListeners()after changes. ChangeNotifierProvider(create: ...)puts it above the app.Provider.of<T>(context)listens; addlisten: falsein callbacks.
Full Code (Copy-Paste Reference)
Everything the app needs up to and including this lecture, file by file.
lib/theme_provider.dart
import 'package:flutter/material.dart';
class ThemeProvider extends ChangeNotifier {
// Private - can only change through toggle(), never set directly from outside.
ThemeMode _themeMode = ThemeMode.light;
ThemeMode get themeMode => _themeMode;
bool get isDark => _themeMode == ThemeMode.dark;
void toggle() {
_themeMode = isDark ? ThemeMode.light : ThemeMode.dark;
// Rings the bell: every widget listening to this provider rebuilds now.
notifyListeners();
}
}lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'theme_provider.dart';
void main() {
runApp(
// Wraps the whole app so ANY widget below, however deep, can reach ThemeProvider.
ChangeNotifierProvider(
create: (context) => ThemeProvider(),
child: const NotesApp(),
),
);
}
class NotesApp extends StatelessWidget {
const NotesApp({super.key});
@override
Widget build(BuildContext context) {
// Listens: this widget rebuilds whenever ThemeProvider calls notifyListeners().
final themeProvider = Provider.of<ThemeProvider>(context);
return MaterialApp(
title: 'My Notes',
debugShowCheckedModeBanner: false,
theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal)),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.teal,
brightness: Brightness.dark,
),
),
themeMode: themeProvider.themeMode,
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('My Notes'),
actions: [
IconButton(
tooltip: 'Toggle theme',
icon: const Icon(Icons.brightness_6),
onPressed: () {
// listen: false - this is a callback, not build(); we only want to CALL
// toggle(), not rebuild this widget every time the theme changes.
Provider.of<ThemeProvider>(context, listen: false).toggle();
},
),
],
),
body: const Center(child: Text('Buy milk and bread')),
);
}
}