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.