你得到的错误不是_notificationsActionStreamSubscription引起的。
如果你仔细阅读它说
流已被收听
这意味着AwesomeNotifications().actionStream 可能一次只能处理一个侦听器。
_notificationsActionStreamSubscription.cancel() 似乎不起作用,AwesomeNotifications().actionStream 可能不知道流侦听器已关闭。
每次推送页面时,都会重新构建它,AwesomeNotifications() 会抛出错误,因为它认为您正在附加第二个侦听器。
所以我提出了这个解决方案:将notificationsActionStreamSubscription 移动到HomeView 的父小部件。
在父级中创建实例,然后将其附加到 actionStream。
每次调用Navigator.pushReplacement将其作为参数发送。
HomeView:(我将其设为 statefullwidget)
class HomeView extends StatefulWidget {
final StreamSubscription<ReceivedAction> notificationsActionStreamSubscription;
const HomeView({Key key, @required this.notificationsActionStreamSubscription}) : super(key: key);
@override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
//You can access with widget.notificationsActionStreamSubscription
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('HomeView '),
),
body: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [],
)
],
),
),
);
}
}
在您的父小部件中(我想它是一个有状态的小部件):
StreamSubscription<ReceivedAction> notificationsActionStreamSubscription;
@override
void initState() {
super.initState();
notificationsActionStreamSubscription =
AwesomeNotifications().actionStream.listen((receivedNotification) {
print(
"user tapped on notification " + receivedNotification.id.toString());
});
}
而且每次推送 HomeView 时:
Navigator.of(context).popUntil((route) => route.isFirst);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => HomeView(notificationsActionStreamSubscription:
notificationsActionStreamSubscription)));
通过这样做,notificationsActionStreamSubscription 将不会在您每次推送HomeView 时重新构建并附加到AwesomeNotifications().actionStream。