On this page14 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. context.watch and context.read
  5. 2. The Updated ThemeProvider
  6. 3. Consumer: Rebuild Only a Part
  7. Code Examples
  8. Common Beginner Mistakes
  9. Best Practices
  10. Mini Challenge
  11. Practice Questions
  12. Practice Answers
  13. Key Takeaways
  14. Full Code (Copy-Paste Reference)

Lecture 005: watch, read & Consumer: A Dark-Mode Switch

Category2: Provider
Lecture005 of 008
Estimated video length14 min
TargetFlutter 3.44 · Dart 3.12 · provider 6.1
LevelBeginner

Provider.of<ThemeProvider>(context, listen: false) is a mouthful. Provider has shorter ways to say the same thing: context.watch, context.read and the Consumer widget. 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 SwitchListTile to the provider
  • Change the theme from a screen pushed with Navigator

1. context.watch and context.read

Short formLong formUse 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
dart
// 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

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:

dart
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

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

dart
onChanged: (value) => context.watch<ThemeProvider>().setDark(value),
code
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:

code
Error: Could not find the correct Provider<ThemeProvider> above this ... Widget

App-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) beats toggle() 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

  1. What's the short form of Provider.of<T>(context, listen: false)?
  2. Which should a Text showing provider data use: watch or read?
  3. What does Consumer give you that context.watch in build doesn't?
  4. Why did the Settings screen work even though it was pushed with Navigator?
  5. What's wrong with onPressed: () => context.watch<ThemeProvider>().setDark(true)?

Practice Answers

  1. context.read<T>().
  2. watch, so it updates when the data changes.
  3. It rebuilds only the widgets inside its builder, not the whole screen.
  4. The provider is above MaterialApp, so every route can reach it.
  5. watch can't be used in a callback; use read.

Key Takeaways

  • context.watch<T>() = read + rebuild on change; use it in build.
  • context.read<T>() = just read; use it in callbacks.
  • Consumer<T> rebuilds only part of the tree.
  • A provider above MaterialApp reaches 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

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

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),
          ),
        ],
      ),
    );
  }
}