Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Sink and Stream in Flutter?

The Google I/O 2018 video about Flutter explains how to use Dart streams to manage state in a Flutter application. The speaker talked about using Sink as input stream and Stream as output stream. What is the difference between Sink and Stream? I searched the documentation but it doesn't say too much thanks.

like image 758
Toni Joe Avatar asked May 15 '18 12:05

Toni Joe


People also ask

What is sink and stream in Flutter?

Streams and sinks are backbones in Dart and Flutter asynchronous programming. At the point when we talk about Streams explicit to dart. We will utilize the async library given by a dart. This library upholds asynchronous programming and contains every one of the classes and techniques to make Streams.

What is the use of streams in Flutter?

In flutter, streams are usually used with the StreamBuilder which manages and unsubscribes from a stream for you internally once the widget is destroyed. A good rule to follow is when you subscribe to a stream, keep the Subscription and write the code in the dispose method to call cancel.

What are different types of streams in Flutter?

There are two types of streams in Flutter: single subscription streams and broadcast streams. Single subscription streams are the default.

What is stream and StreamBuilder in Flutter?

StreamBuilder is a widget that builds itself based on the latest snapshot of interaction with a stream.


1 Answers

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.

like image 177
Abin Avatar answered Sep 22 '22 21:09

Abin