FirebaseMessaging.onMessage.listen流控制器不工作

rlcwz9us  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(166)

我正在听FirebaseMessaging.onMessage。print语句按预期工作,但我想添加RemoteMessagestreamController不工作。

FirebaseMessaging.onMessage.listen((message) {
    _streamController.add(message);
    print(message.notification?.body ?? 'empty body'); // working perfectly
        });

这里是streamcontroller

final StreamController<RemoteMessage> _streamController = StreamController();

  Stream<RemoteMessage> notificationStream() {
    return _streamController.stream;
  }

这是我听流的地方:

class _HomePageState extends State<HomePage> {
  late Stream<RemoteMessage> _stream;
  @override
  void initState() {
    _stream = NotificationService().notificationStream();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home'),
      ),
      body: StreamBuilder(
        stream: _stream,
        builder: (context, snapshot) {
          if (snapshot.hasData) return Text(snapshot.data!.notification!.body!);
          return const Text('empty snapshot');
        },
      ),
    );
  }
}
cnjp1d6j

cnjp1d6j1#

问题出在我的单例实现上,我把它改成了

class NotificationService {
  NotificationService._();
  static final NotificationService instance = NotificationService._();
  ...
  ...
}

相关问题