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
相关产品推荐
相关产品推荐

