每当流获得新值时如何显示对话框?

问题描述 投票:0回答:1

我有以下bloc提供商

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,并且在添加新值时通知会正确显示

StreamBuilder(
  stream: cloudMessagingBloc.stream,
  builder: (BuildContext context, AsyncSnapshot<NotificationModel> snapshot) {
    if (snapshot.connectionState == ConnectionState.active && snapshot.hasData)
      SchedulerBinding.instance
          .addPostFrameCallback((_) => _showNotificationDialog(context, snapshot.data));

但是问题是,只要重建包含此streambuilder的小部件,由于满足条件,该通知就会再次显示,这不是我想要的,因为我只想显示一次通知。那么如何防止这种情况发生呢?感觉像是我遇到了结构性问题,只是无法解决。

flutter dart stream
1个回答
1
投票

我看到3种可能的解决方案:

© www.soinside.com 2019 - 2024. All rights reserved.