我在 Flutter 项目中有使用
riverpod
的函数。
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);
}
当用户退出这个小部件时,我需要运行这些功能。
所以在
dispose()
方法中,我在 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();
}
但我仍然收到错误:
Bad state: Cannot use "ref" after the widget was disposed.
我试图让 super.dispose() 在 2 秒后运行。
Future.delayed(const Duration(seconds: 2), () {
super.dispose();
});
但它在 dispose() 部分崩溃了。
而且我也无法将 dispose() 设为异步/等待。
如何做到这一点?
因为 dispose 函数不能异步,即使 Future.delayed 有效,它也不是最好的解决方案,您可以考虑解决此问题的解决方法。
我有2条建议:
1st 您可以使用 PopScope 小部件包装您的小部件,在“退出”小部件之前,您可以运行 _deleteChatRoom() 和 _updateChatTime() 方法,然后手动调用导航弹出方法这将触发 dispose 方法,并关闭小部件。 (如果您有其他退出小部件的方式,例如“x”按钮,您可以将这些方法调用移动到那里)
2nd我不知道你的应用程序的架构,但我想你可以更改 ref 变量的范围,这样你就可以调用 _deleteChatRoom() 和 _updateChatTime() 方法而不依赖于在子部件上。
重要 由于没有足够的代码,此解决方案可能不是 100% 适用,但您可以获得有关如何解决问题的提示。如果您能提供有关小部件如何组织、导航方式以及您正在使用的状态管理的更多信息,那就最好了。