I’m working with Flutter Riverpod and have encountered different behaviors when using ref.watch versus ref.read in my DumTabNotifier class. Here’s a simplified version of my code:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:get/get.dart';
// Notifier class
class DumTabNotifier extends Notifier<DumTabState> {
final _edtLmp = TextEditingController();
@override
DumTabState build() {
ref.onDispose(() {
_edtLmp.clear();
});
return DumTabState(
gestationalAgeString: '',
edd: '',
eofTrimester: '',
bofTrimester: '',
gaWeeks: 0,
gaDays: 0,
edtLmp: _edtLmp,
);
}
void calculateFromLmp() {
DateTime? lmpDT = extractDateFromStringBasedOnLocale(_edtLmp.text);
if (lmpDT == null) return;
final todayGlobal = ref.watch(todayGlobalProvider); // or ref.read(todayGlobalProvider)
// Calculation logic...
}
}
final dumTabProvider = NotifierProvider<DumTabNotifier, DumTabState>(() {
return DumTabNotifier();
});
Issue:
When I use ref.watch(todayGlobalProvider) inside calculateFromLmp(), the DumTabNotifier gets disposed and recreated if the todayGlobalProvider changes. I discovered this because the TextEditingController (_edtLmp) clears itself (unwanted behavior) whenever ref.watch is used, indicating that the notifier is being disposed. However, when I replace ref.watch with ref.read(todayGlobalProvider), the DumTabNotifier is not disposed when todayGlobalProvider changes.
Question:
Why does using ref.watch cause the DumTabNotifier to be disposed and recreated, while ref.read does not?
What are the best practices for deciding when to use ref.watch versus ref.read in this context?
Any insights into the behavior and lifecycle management of Riverpod notifiers would be greatly appreciated!