Member-only story
FLUTTER INTERVIEW QUESTIONS
What is a StreamBuilder in Flutter and how it really works?
As almost everything in Flutter, StreamBuilder is a Widget and as you can assume - it rebuilds its UI according to the new values that are passed via Stream it listens to.
In the example below, we generate 10 random colors from periodic Timer(each second new color gets generated) and pass it to the stream. Our StreamBuilder listens to the events from provided Stream and changes Container’s background color to the newly fetched one.
Pretty simple, right?
Yes, but builder is using an AsyncSnapshot, not a Stream. What is that?
AsyncSnapshot is a class that wraps latest received data from the Stream, connectionState and an error.
During the initState() phase in the StreamBuilder Widget, listening to the provided stream starts:
..when new value via stream arrives, new snapshot gets created: