On this page16 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. The Problem With Passing Callbacks
  5. 2. Adding Provider
  6. 3. A ChangeNotifier: State Plus a Bell
  7. 4. ChangeNotifierProvider: Put It Above the App
  8. 5. Reading It: Provider.of
  9. Code Examples
  10. Common Beginner Mistakes
  11. Best Practices
  12. Mini Challenge
  13. Practice Questions
  14. Practice Answers
  15. Key Takeaways
  16. Full Code (Copy-Paste Reference)

Lecture 004: Why Provider? A ThemeProvider With ChangeNotifier

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

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 provider package
  • Write a ThemeProvider that extends ChangeNotifier and calls notifyListeners()
  • Put it above the app with ChangeNotifierProvider
  • Read it with Provider.of, with and without listen: false

1. The Problem With Passing Callbacks

code
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

bash
flutter pub add provider

This adds provider: ^6.1.5+1 (or newer) to pubspec.yaml. Then import it where needed:

dart
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

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 through toggle().
  • toggle() changes the data, then rings the bell with notifyListeners().

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:

dart
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

dart
// 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();
CallRebuilds on change?Use it…
Provider.of<T>(context)yesin build, to show data
Provider.of<T>(context, listen: false)noin 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

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:

  1. toggle() changes _themeMode and calls notifyListeners().
  2. NotesApp is listening (Provider.of without listen: false), so it rebuilds.
  3. MaterialApp gets the new themeMode, 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()

dart
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

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

ChangeNotifierProvider must wrap the widgets that read it. Put it in main(), around the whole app.

3. Listening inside a button handler

dart
onPressed: () => Provider.of<ThemeProvider>(context).toggle(),

Tapping it fails with:

code
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 maybe CartProvider).
  • Keep fields private and change them only through methods that call notifyListeners().
  • Put app-wide providers in main(), above MaterialApp.

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

  1. What is "prop drilling"?
  2. What does notifyListeners() do?
  3. Where should ChangeNotifierProvider go for an app-wide setting?
  4. When do you pass listen: false?
  5. What happens if you forget notifyListeners()?

Practice Answers

  1. Passing data or callbacks down through widgets that don't use them, just to reach a deeper widget.
  2. It tells every listening widget to rebuild.
  3. In main(), wrapping the whole app.
  4. In event handlers like onPressed, where you only want to call a method, not rebuild.
  5. The data changes but the screen doesn't update.

Key Takeaways

  • Provider shares state with any widget below it, without passing callbacks around.
  • A ChangeNotifier holds the state and calls notifyListeners() after changes.
  • ChangeNotifierProvider(create: ...) puts it above the app.
  • Provider.of<T>(context) listens; add listen: false in callbacks.

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 {
  // 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

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