Optimal use of StreamBuilder?

61 Views Asked by At

The FutureBuilder doc says

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

I'm guessing the same is true for StreamBuilder but that doc doesn't give similar guidance. Is StreamBuilder fundamentally different from FutureBuilder in this regard?

Thanks!

1

There are 1 best solutions below

2
MendelG On

Yes, you should also initiate the StreamBuilder within the initState, as discussed in my previous Q/A about FutureBuilder.

This approach prevents unnecessary repainting of your UI and StreamBuilder with each rebuild (for example, when triggered by setState).


The reason (I think) why it's only updated in the documentation for FutureBuilder is since they needed to edit the documentation after a proposed issue explaining why you should use initState.