Search code examples
flutterriverpodflutter-change-notifierflutter-change-notifier-provider

Why do we need ChangeNotifierProvider instead of just using a ChangeNotifier?


I am trying to learn how to use flutter_riverpod for state management, I am having trouble understanding what the "need" for ChangeNotifierProvider is , same thing for StateNotifierProvider. Let's take the following ChangeNotifier for example :

class CounterNotifier extends ChangeNotifier {
  int value = 0;

  void increment() {
    value++;
    notifyListeners();
  }
}

Why is it "advised" to declare a ChangeNotifierProvider for my ChangeNotifier and use it to watch() and read() the value of my ChangeNotifier like so:

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final counterProvider = ChangeNotifierProvider((ref) => CounterNotifier());


class ChangeCounterPage extends ConsumerWidget {
  const ChangeCounterPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
        
          ref.read(counterProvider).increment();
        },
        child: const Icon(Icons.add),
      ),
      body: Center(
       
        child: Text(ref.watch(counterProvider).value.toString()),
      ),
    );
  }
}

Why not just use the ChangeNotifier (like we do with provider) ? in the official documentation of riverpod it says : " we are using the ChangeNotifierProvider to allow the UI to interact with our ChangeNotifier class." -> what does that mean ? is ChangeNotifierProvider a widget that wraps around the ChangeNotifier and thus makes is "visible" in the widget tree ? I've also read that it makes the "manipulation" of our state easier or more manageable but I can't understand why or how it is needed.


Solution

  • A ChangeNotifier must be listened, with an action associated with change events, in order to be useful. It also must be unlistened before the listener goes away.

    A ChangeNotifierProvider wraps the process of listening to a ChangeNotifier into a "ProviderListener" protocol, which knows how to make the widget watching the provider rebuild when events occur, and how to disconnect itself when the widget is disposed.