12

I have StreamBuilder

Widget build(BuildContext context) {
  return StreamBuilder(
    initialData: false,
    stream: widget.stream, ...

For initializing widget I call:

_EventSpeakerPager(..., streamController.stream.distinct());

And this produce error "Bad state: Stream has already been listened to." Without distinct() it works, but it's not suitable for me.

I've tried asBroadcastStream() and got the same error

Does anybody know, how can I handle this

P.S. I've already looked into these:

topic1, topic2, topic3 - nothing helps

P.P.S. When I use stream without StreamBuilder - all works fine

void initState() {
super.initState();
widget.stream.listen((bool data) {
  setState(() {
    ...
  });
});

}

Andrii Turkovskyi
  • 27,554
  • 16
  • 95
  • 105

2 Answers2

37

So, all I've needed to do is replace

final StreamController<bool> streamController = StreamController<bool>();

with final StreamController<bool> streamController = StreamController<bool>.broadcast();

Andrii Turkovskyi
  • 27,554
  • 16
  • 95
  • 105
10

Use the rx_dart library from pubspec: https://pub.dartlang.org/packages/rxdart

Now change your Stream<Something> declaration to be a BehaviorSubject<Something>. (The BehaviorSubject is a kind of stream that has memory of the last value transmited. There is other subjects available on the library like the PublishSubject and the ReplaySubject, check their docs for your use case).

The rx_dart library is an extension of the Stream base classes and are much more powerful and easier to work.

Check their GitHub: https://github.com/ReactiveX/rxdart

Daniel Oliveira
  • 8,053
  • 11
  • 40
  • 76
  • 5
    I don't need rx - as I wrote above - I can do it without StreamBuilder and it works totally fine. I don't want to add additional dependencies. Just trying to figure out and solve this. – Andrii Turkovskyi Oct 19 '18 at 06:15
  • As I said, rx_dart is an extension to the default Stream dart objects. RX_dart fixes some issues that the stream classes has. One of the them is the "broadcast-type" for streams. – Daniel Oliveira Oct 19 '18 at 13:27
  • @DanielOliveira Is it really important to use rxDart? i have the same problem and .broadcast() fixes the problem. `RX_dart fixes some issues that the stream classes has` Stream class has bugs? should i use Rxdart? – Mahesh Mar 01 '20 at 17:29
  • When I said "issues" I was refering to "missing of features". It is built over the standard Stream classes (and they work really well) – Daniel Oliveira Mar 02 '20 at 16:00
  • I tried `StreamController.broadcast()`, but I had so many problem! After switching to rx_dart my life is much better :) Thanks guys for the tip! – Rebar Jun 10 '21 at 01:41