gpt4 book ai didi

flutter - Awesome_Notifications - 状态错误 : Stream has already been listened to

转载 作者:行者123 更新时间:2023-12-04 03:36:45 28 4
gpt4 key购买 nike

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

_notificationsActionStreamSubscription = AwesomeNotifications().actionStream.listen((receivedNotification) {
print("user tapped on notification " + receivedNotification.id.toString());
});
稍后当有人登录或退出我的应用程序时,我会调用这些行:
Navigator.of(context).popUntil((route) => route.isFirst);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => HomeView()));
这是 initState()我的 HomeView再次调用导致错误:
Bad state: Stream has already been listened to.
这就是为什么我在从上面调用两条 Navigator 行之前这样做了,但没有成功:
AwesomeNotifications().createdSink.close();
_notificationsActionStreamSubscription.cancel();
我究竟做错了什么?我取消了流订阅,为什么我仍然收到此错误消息?
谢谢你的建议!

最佳答案

您得到的错误不是由 _notificationsActionStreamSubscription 引起的.
如果你仔细阅读它说

Stream has already been listened to


这意味着可能 AwesomeNotifications().actionStream一次只能处理一个听众。 _notificationsActionStreamSubscription.cancel()似乎不起作用,可能是 AwesomeNotifications().actionStream不知道流监听器已关闭。
每次页面被推送时,它都会被重建,并且 AwesomeNotifications()抛出错误,因为它认为您正在附加第二个监听器。
所以我提出了这个解决方案: 移动 notificationsActionStreamSubscriptionHomeView 的父小部件.
在父级中创建实例,然后将其附加到 actionStream。
每次打电话 Navigator.pushReplacement 将其作为参数发送 .
首页查看 :(我把它变成了一个有状态的小部件)
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不会被重建和附加到 AwesomeNotifications().actionStream每次推 HomeView .

关于flutter - Awesome_Notifications - 状态错误 : Stream has already been listened to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66754739/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com