Kernel James
Kernel James

Reputation: 4064

Call Stream.stream.listen() twice with StreamBuilder?

I am using StreamBuilder and putting an instance of StreamController.stream into it.

late StreamController c;
late Stream s;

initState() {
  c = StreamController();
  s = c.stream;
  super.initState();
}

Widget build(context) {
  return StreamBuilder(
    stream: s,
    builder: (context, snap) {
      return Container(
        child: TextButton(
          onPressed:() => setState(() {
            //calling setState will re-build StreamBuilder
          }),
        ),
      };
    }
  );
}

Since the StreamBuilder will be rebuilt on every setState call, how do I prevent StreamBuilder from trying to re-listen to Stream without making it a Broadcast stream (since Streams can only be listened to once)?

Upvotes: 0

Views: 1146

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17113

A StreamBuilder doesn't do anything with its stream when it's rebuilt if the stream is the same. There is no re-listening so it's not necessary to do anything special here.

Evidence can be found in the implementation of StreamBuilder and StreamBuilderBase in the Flutter source. Action is only taken if the new stream differs from the old one.

@override
void didUpdateWidget(StreamBuilderBase<T, S> oldWidget) {
  super.didUpdateWidget(oldWidget);
  if (oldWidget.stream != widget.stream) {
    if (_subscription != null) {
      _unsubscribe();
      _summary = widget.afterDisconnected(_summary);
    }
    _subscribe();
  }
}

Upvotes: 2

Related Questions