Awesome_Notifications - 错误状态:流已被收听

pro*_*bie 9 flutter

我正在使用这个flutter 库来处理通知。在initState()我的HomeView初始化这个监听器中:

_notificationsActionStreamSubscription = AwesomeNotifications().actionStream.listen((receivedNotification) {
  print("user tapped on notification " + receivedNotification.id.toString());
});
Run Code Online (Sandbox Code Playgroud)

稍后,当有人登录或退出我的应用程序时,我会调用以下行:

Navigator.of(context).popUntil((route) => route.isFirst);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => HomeView()));
Run Code Online (Sandbox Code Playgroud)

这让initState()HomeView再次被调用,这会导致错误:

Bad state: Stream has already been listened to.
Run Code Online (Sandbox Code Playgroud)

这就是为什么我在从上面调用两条导航器行之前执行此操作,但没有成功:

AwesomeNotifications().createdSink.close();
_notificationsActionStreamSubscription.cancel();
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我取消了流订阅,为什么我仍然收到此错误消息?

谢谢你的建议!

Ash*_*shB 3

根据文档,侦听器应该是顶级函数并在 main.dart 文件中实现。您基本上应该将所有侦听器移动到不同的函数或类,然后在主函数中调用它

void main(){
  WidgetsFlutterBinding.ensureInitialized();
  notificationInit();
  runApp(MaterialApp(home: YourApp()));
}

void notificationInit() async {
  await AwesomeNotifications.initialize(...);
  _notificationsActionStreamSubscription = ...;
  _notificationsCreatedStreamSubscription = ...;
  _notificationsDisplayedStreamSubscription = ...;
  _notificationsDismissedStreamSubscription = ...;
}
Run Code Online (Sandbox Code Playgroud)