I have functions that use riverpod
in Flutter project.
Future<void> _deleteChatRoom() async {
try {
await ref.read(chatRepo).deleteChatRoom(_roomId);
} catch (e) {
// ignore: avoid_print
print("_deleteChatRoom -> $e");
}
}
Future<void> _updateChatTime() async {
Duration duration = DateTime.now().difference(_chatStartTime);
int chatTime = duration.inSeconds;
await ref.read(chatRepo).updateChatTime(_roomId, chatTime);
}
And when user exit this Widget, I need to run these functions.
So in dispose()
method, I run them before super.dispose()
.
@override
void dispose() {
if (chatList.isEmpty) {
_deleteChatRoom();
} else {
_updateChatTime();
}
_messageController.dispose();
_scrollController.dispose();
_answerTypingController.close();
_animationController.dispose();
_speechToText.stop();
_flutterTts.stop();
super.dispose();
}
But still I get error:
Bad state: Cannot use "ref" after the widget was disposed.
I tried to make super.dispose() to be run after 2 seconds.
Future.delayed(const Duration(seconds: 2), () {
super.dispose();
});
But it crashes in dispose() part.
And also I can’t make dispose() to be async/ await.
How to make this work?