You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用Riverpod监听Firebase Messaging onMessage流无触发的问题求助

Flutter中使用Riverpod监听Firebase Messaging onMessage流无触发的问题求助

我刚接触Flutter,现在正在用Firebase Messaging和Riverpod做状态管理开发一个应用。我参考了相关思路,把全局监听的初始化从main.dart抽离到单独的类里,用Riverpod来管理。

但是遇到一个棘手的问题:直接订阅FirebaseMessaging.onMessage流的时候,监听器能正常触发并打印消息;但用ref.listen监听对应的StreamProvider时,事件处理函数完全没反应,我实在找不到哪里出错了,想请教下各位大佬。

下面是我的相关代码:

定义监听FCM前台消息的StreamProvider

@Riverpod(keepAlive: true)
Stream<RemoteMessage> fcmOnMessage(FcmOnMessageRef ref) {
  return FirebaseMessaging.onMessage;
}

负责通知逻辑的NotificationService类

class NotificationService {
  NotificationService(this.ref) {
    _init();
  }

  final Ref ref;

  void _init() {
    // 直接订阅流的话,这个监听器能正常触发并打印内容
    FirebaseMessaging.onMessage.listen((message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');
      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });

    // 用Riverpod的ref.listen监听却完全没反应
    ref.listen(fcmOnMessageProvider, (previous, next) {
      final remoteMessage = next.value;
      debugPrint("onForegroundMessage: ${remoteMessage?.notification?.title}");
      debugPrint("onForegroundMessage: ${remoteMessage?.notification?.body}");
    });
  }
}

提供NotificationService的Provider

@riverpod
NotificationService notificationService(NotificationServiceRef ref) {
  return NotificationService(ref);
}

main.dart初始化代码

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  FirebaseMessaging.instance.setAutoInitEnabled(true);
  FirebaseMessaging.instance.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true
  );

  final container = ProviderContainer();
  container.read(notificationServiceProvider);

  runApp(
    UncontrolledProviderScope(
      container: container,
      child: const MyApp(),
    )
  );
}

有没有大佬能帮我分析下,为什么用Riverpod的方式监听不到流事件呀?

备注:内容来源于stack exchange,提问作者user501211

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 09:09:38