EndUserViewModel? endUserViewModel;
@override
void initState() {
super.initState();
if(mounted){
loadEndUser();
}
}
loadEndUser() async {
WidgetsBinding.instance.addPostFrameCallback((_) async {
endUserViewModel = ref.read(endUserViewModelProvider.notifier);
await endUserViewModel?.fetchEndUser("[email protected]");
final endUser = endUserViewModel?.endUserList;
final endUserData = endUser?.first.name;
print(" DATA $endUser");
print("USER $endUserData");
});
}
I am trying to fetch the data from the API using this function in initState()
,
but it shows the error-
E/flutter (14175): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: Tried to use EndUserViewModel after `dispose` was called.
E/flutter (14175):
E/flutter (14175): Consider checking `mounted`.
I have also used ConsumerStateful
for the class and checked the mounted but it does not work.
3
Answers
Hello, move the if (mounted) check inside the WidgetsBinding.instance.addPostFrameCallback() callback, this ensure that the loadEndUser() method is only called if the widget is still mounted. This check is necessary because the addPostFrameCallback() method schedules a callback to be called after the frame is rendered. If the widget is unmounted before the frame is rendered, the callback will not be executed.
dragonpicari is right, but be sure to always check, that the widget is still mounted after async methods.
But in this case the post frame callback is not necessary, you are able to load it in initState().