Flutter : Bad state: Stream has already been listened to

前端 未结 11 1333
灰色年华
灰色年华 2020-12-03 04:21

    class MyPage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Defaul         


        
11条回答
  •  一整个雨季
    2020-12-03 04:36

    In my case, I was getting this error because the same line of code myStream.listen() was being called twice in the same widget on the same stream. Apparently this is not allowed!

    UPDATE: If you intend to subscribe to the same stream more than once, you may want to choose behavior subject instead:

    final _myController = BehaviorSubject();
    // use myStream.listen((latestEvent) {// run code when event is received});
    Stream get myStream =>
          _myController.stream;
    // use myStreamInputSink.add('new event'); to trigger events
    Sink get mySteamInputSink => _myController.sink;
    

    OR If a widget subscribes to a stream, and this widget is destroyed then redrawn which results for its new instance to subscribe to the same listener a second time, it's best to reset on widget dispose:

    _flush() {
      _myController.close();
      _myController = StreamController();
    }
    

    Old Answer:

    What fixed it for me is to both create a my stream controller as a broadcast stream controller:

    var myStreamController = StreamController.broadcast();
    

    AND

    use stream as a broadcast stream:

    myStreamController.stream.asBroadcastStream().listen(onData);
    

提交回复
热议问题