On this page14 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. context.watch and context.read
- 2. The Updated ThemeProvider
- 3. Consumer: Rebuild Only a Part
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Key Takeaways
- Full Code (Copy-Paste Reference)
Lecture 005: watch, read & Consumer: A Dark-Mode Switch
| Category | 2: Provider |
| Lecture | 005 of 008 |
| Estimated video length | 14 min |
| Target | Flutter 3.44 · Dart 3.12 · provider 6.1 |
| Level | Beginner |
Provider.of<ThemeProvider>(context, listen: false)is a mouthful. Provider has shorter ways to say the same thing:context.watch,context.readand theConsumerwidget. With them, we build a real Settings screen whose switch changes the whole app.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lecture 004 (ChangeNotifier, ChangeNotifierProvider, Provider.of), and Navigator.push
(Essential Widgets).
Connection With Previous Lectures
toggle() becomes setDark(bool), which suits a switch, and the toggle button moves to a new
Settings screen, proving Provider works across screens.
Learning Objectives
- Use
context.watch<T>()to read and listen - Use
context.read<T>()to call methods without listening - Rebuild just part of a screen with
Consumer<T> - Connect a
SwitchListTileto the provider - Change the theme from a screen pushed with
Navigator
1. context.watch and context.read
| Short form | Long form | Use in |
|---|---|---|
context.watch<ThemeProvider>() | Provider.of<ThemeProvider>(context) | build: show data, rebuild on change |
context.read<ThemeProvider>() | Provider.of<ThemeProvider>(context, listen: false) | callbacks: call methods |
// in build:
final isDark = context.watch<ThemeProvider>().isDark;
// in a callback:
onChanged: (value) => context.read<ThemeProvider>().setDark(value),A simple rule: watch to show, read to change.
2. The Updated ThemeProvider
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 setDark(bool value) {
_themeMode = value ? ThemeMode.dark : ThemeMode.light;
notifyListeners();
}
}A switch tells you the new value (true/false), so setDark(bool) fits better than toggle().
3. Consumer: Rebuild Only a Part
context.watch in build rebuilds the whole widget. Consumer rebuilds only what's inside
its builder:
Consumer<ThemeProvider>(
builder: (context, theme, child) {
return Text(theme.isDark ? 'Dark mode is on' : 'Light mode is on');
},
)The builder gets the provider as its second argument (theme). Use Consumer when only a
small piece of a big screen depends on the provider.
Code Examples
Example 1: A Settings Screen With a Dark-Mode Switch
lib/theme_provider.dart: as in Section 2.
lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'theme_provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => ThemeProvider(),
child: const NotesApp(),
),
);
}
ThemeData buildTheme(Brightness brightness) {
return ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal, brightness: brightness),
);
}
class NotesApp extends StatelessWidget {
const NotesApp({super.key});
@override
Widget build(BuildContext context) {
final themeMode = context.watch<ThemeProvider>().themeMode;
return MaterialApp(
title: 'My Notes',
debugShowCheckedModeBanner: false,
theme: buildTheme(Brightness.light),
darkTheme: buildTheme(Brightness.dark),
themeMode: 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: 'Settings',
icon: const Icon(Icons.settings),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SettingsScreen()),
),
),
],
),
body: Center(
child: Consumer<ThemeProvider>(
builder: (context, theme, child) {
return Text(theme.isDark ? 'Dark mode is on' : 'Light mode is on');
},
),
),
);
}
}
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
final isDark = context.watch<ThemeProvider>().isDark;
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: ListView(
children: [
SwitchListTile(
title: const Text('Dark mode'),
secondary: const Icon(Icons.dark_mode),
value: isDark,
onChanged: (value) => context.read<ThemeProvider>().setDark(value),
),
],
),
);
}
}Try it: the home screen says Light mode is on. Tap ⚙, flip the switch, and the Settings screen turns dark at once. Go back: the home screen is dark too and says Dark mode is on. Three widgets on two screens stay in sync, and no callback was passed anywhere.
Tested: flipping the switch set MaterialApp.themeMode to ThemeMode.dark, turned the switch
on, and changed the home text.
Common Beginner Mistakes
1. watch in a callback
onChanged: (value) => context.watch<ThemeProvider>().setDark(value),Tried to listen to a value exposed with provider, from outside of the widget tree.Callbacks use read.
2. read in build to show data: Text('${context.read<ThemeProvider>().isDark}') shows
the value once and never updates. Showing data means watch (or Consumer).
3. A provider created on a pushed screen: if ChangeNotifierProvider wraps only
HomeScreen, the Settings route (pushed above it) can't find it:
Error: Could not find the correct Provider<ThemeProvider> above this ... WidgetApp-wide providers go above MaterialApp, in main().
Best Practices
- Watch to show, read to change.
- Use
Consumer(or a small separate widget) when only part of a big screen depends on the provider. - Give provider methods clear intent-based names:
setDark(true)beatstoggle()for a switch.
Mini Challenge
Add a second SwitchListTile titled "Large text" with a bool largeText in ThemeProvider.
When it's on, use textTheme: Typography.material2021().black.apply(fontSizeFactor: 1.2) in the
light theme (and .white in the dark one).
Practice Questions
- What's the short form of
Provider.of<T>(context, listen: false)? - Which should a
Textshowing provider data use:watchorread? - What does
Consumergive you thatcontext.watchinbuilddoesn't? - Why did the Settings screen work even though it was pushed with
Navigator? - What's wrong with
onPressed: () => context.watch<ThemeProvider>().setDark(true)?
Practice Answers
context.read<T>().watch, so it updates when the data changes.- It rebuilds only the widgets inside its
builder, not the whole screen. - The provider is above
MaterialApp, so every route can reach it. watchcan't be used in a callback; useread.
Key Takeaways
context.watch<T>()= read + rebuild on change; use it inbuild.context.read<T>()= just read; use it in callbacks.Consumer<T>rebuilds only part of the tree.- A provider above
MaterialAppreaches every screen, including pushed routes. - Next: the choice is forgotten when the app restarts. SharedPreferences fixes that.
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 {
ThemeMode _themeMode = ThemeMode.light;
ThemeMode get themeMode => _themeMode;
bool get isDark => _themeMode == ThemeMode.dark;
// Takes the new value directly - fits a Switch better than a plain toggle().
void setDark(bool value) {
_themeMode = value ? ThemeMode.dark : ThemeMode.light;
notifyListeners();
}
}lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'theme_provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => ThemeProvider(),
child: const NotesApp(),
),
);
}
ThemeData buildTheme(Brightness brightness) {
return ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal, brightness: brightness),
);
}
class NotesApp extends StatelessWidget {
const NotesApp({super.key});
@override
Widget build(BuildContext context) {
// watch = short for Provider.of<T>(context); rebuilds this widget on every change.
final themeMode = context.watch<ThemeProvider>().themeMode;
return MaterialApp(
title: 'My Notes',
debugShowCheckedModeBanner: false,
theme: buildTheme(Brightness.light),
darkTheme: buildTheme(Brightness.dark),
themeMode: 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: 'Settings',
icon: const Icon(Icons.settings),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SettingsScreen()),
),
),
],
),
body: Center(
// Consumer rebuilds only this Text, not the whole HomeScreen.
child: Consumer<ThemeProvider>(
builder: (context, theme, child) {
return Text(theme.isDark ? 'Dark mode is on' : 'Light mode is on');
},
),
),
);
}
}
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
// Pushed with Navigator, yet still reaches the provider - it's above MaterialApp.
final isDark = context.watch<ThemeProvider>().isDark;
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: ListView(
children: [
SwitchListTile(
title: const Text('Dark mode'),
secondary: const Icon(Icons.dark_mode),
value: isDark,
// read = short for Provider.of<T>(context, listen: false): a callback, not build().
onChanged: (value) => context.read<ThemeProvider>().setDark(value),
),
],
),
);
}
}