Reputation: 1
Here is the partial code of my page:
@override
void initState() {
super.initState();
ref
.read(disableTimeControllerProvider.notifier)
.initStateWhenCreate(widget.watchId);
}
@override
Widget build(BuildContext context) {
ClassMode classModeState = ref.watch(disableTimeControllerProvider);
}
Here is the partial code of my provider:
@riverpod
class DisableTimeController extends _$DisableTimeController {
@override
ClassMode build() {
return ClassMode();
}
void initStateWhenCreate(String watchId) {
ClassMode classMode = ClassMode(
watchId: watchId,
classSwitch: 1, //默认开启
classWeek: 31,
holidaySwitch: 1,
timePeriod: [ClassModeTime(startTime: "08:00:00", endTime: "11:30:00")],
type: 0,
);
state = classMode;
}
}
In my widget, I called read before watching, which will initialize the state, but why is it not destroyed immediately, because no one watches it. This results in the subsequent execution of the watch being able to obtain the state modified through read. (It seems that the state initialized by read has survived for a period of time, but what is the reason for this, and how long will read keep the state?) I hope someone can answer my confusion.
Upvotes: -1
Views: 20
Reputation: 885
I think what is happening is pretty normal and riverpod works this way. You are reading and watching inside the same state.
Once you do a read inside the initState, the provider's state is maintained because the widget's state is maintained. When you perform a watch, it reads that maintained state.
I am not quite sure what you are trying to acheive here, why do you initialize it in initState if you don't want to watch it later? Regardless, if you don't want the watch to load an initialized state just don't call .read()
in initState.
Upvotes: 0