What is the difference between Sink and Stream in Flutter?
Sink
and Stream
both are parts of the StreamController
. You add a data to the StreamController
using Sink
which can be listened via the Stream
.
Example:
final _user = StreamController<User>();Sink get updateUser => _user.sink;Stream<User> get user => _user.stream;
Usage:
updateUser.add(yourUserObject); // This will add data to the stream.
Whenever a data is added to the stream via sink, it will be emitted which can be listened using the listen method.
user.listen((user) => print(user));
You can perform a various number of actions before the stream is emitted. transform
method is an example which can be used to transform the input data before it gets emitted.
A StreamSink
is a StreamConsumer
, which means it can take several streams (added by addStream
) and processes the events these streams emit.
If it is the StreamSink
of a StreamController
then all events from the added streams are emitted by the stream created by the StreamController
.
This way you can pipe (forward) one or more streams into another one.
If you are looking for a very basic definitions on stream and sinks, then refer to this:
Stream - the conveyor belt is called as a stream
StreamController - this is what controls the stream
StreamTransformer - this is what processes the input data
StreamBuilder - it’s a method that takes stream as an input and provides us with a builder which rebuilds every time there is a new value of a stream
sink - the property which takes an input
stream - the property which gives the output out of the Stream
For more details, please refer to this article