androidflutterstreamflutter-method-channel

Flutter Bad State: Stream has already been listened to


I am trying to use methodChannel in flutter to receive events from native Android code. But once I cancel the stream subscription I can no longer create new subscriptons even if I set the stream asBroadcastStream()

Receiver.dart

static Stream<dynamic> get accessStream {
  _stream ??= _eventChannel.receiveBroadcastStream().map<dynamic>(
    (event) {
      return MainEvent.fromMap(event);
    },
  );
  return _stream!.asBroadcastStream();
}

When trying to call the function

subs = Receiver.accessStream.listen((event) async {
          if (event != null) {
            events.add(event);
          }
        });

//After Some Time in Cancel Function
await subs.cancel()

It works for the first time but when I call the same function in app_listen.dart again. It gives the following error

[ +100 ms] E/flutter (32159): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Bad state: Stream has already been listened to.
[        ] E/flutter (32159): #0      _StreamController._subscribe (dart:async/stream_controller.dart:676:7)
[        ] E/flutter (32159): #1      _ControllerStream._createSubscription (dart:async/stream_controller.dart:827:19)
[        ] E/flutter (32159): #2      _StreamImpl.listen (dart:async/stream_impl.dart:473:9)
[        ] E/flutter (32159): #3      listenEvent(package:trying/util/struct/app_listen.dart:49:51)
[        ] E/flutter (32159): <asynchronous suspension>

Thanks for answering.


Solution

  • I have solved the issue by just removing the ??= and replacing it with = in Receiver.dart