【发布时间】:2020-05-11 10:52:10
【问题描述】:
我有以下集团供应商
class CloudMessagingBloc{
StreamController<NotificationModel> _streamController = StreamController<NotificationModel>();
Stream<NotificationModel> get stream => _streamController.stream;
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
CloudMessagingBloc() {
if (Platform.isIOS) _firebaseMessaging.requestNotificationPermissions(IosNotificationSettings());
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
_streamController.add(NotificationModel.fromMap(message));
},
onLaunch: (Map<String, dynamic> message) async {
_streamController.add(NotificationModel.fromMap(message));
},
onResume: (Map<String, dynamic> message) async {
_streamController.add(NotificationModel.fromMap(message));
},
);
}
void dispose(){
_streamController.close();
}
}
并像这样实现它
static Widget create() {
return MultiProvider(
providers: [
Provider(create: (_) => DelayBloc(seconds: 2)),
Provider(
create: (_) => CloudMessagingBloc(),
dispose: (BuildContext context, CloudMessagingBloc bloc) => bloc.dispose(),
lazy: false,
),
],
child: TheRootPage(),
);
}
在我的根页面无状态小部件中。但是现在我遇到了一个问题,因为我想在流发出新值时显示一次对话框。所以我为此实施了一个流构建器,当添加新值时,通知会正确显示
StreamBuilder(
stream: cloudMessagingBloc.stream,
builder: (BuildContext context, AsyncSnapshot<NotificationModel> snapshot) {
if (snapshot.connectionState == ConnectionState.active && snapshot.hasData)
SchedulerBinding.instance
.addPostFrameCallback((_) => _showNotificationDialog(context, snapshot.data));
但问题是每当包含此流构建器的小部件重建时,通知都会再次显示,因为满足条件,这不是我想要的,因为我只想显示一次通知。那么我该如何防止这种情况发生呢?感觉就像我有一个结构性问题,我就是想不通。
【问题讨论】: