Keerti Purswani
Keerti Purswani

Reputation: 5381

What is being passed while adding and listening stream and how is it being used?

I have been having hard time working with streams. I read many articles and finally wrote this code. I understand how streams work theoretically but the code isn't making much sense to me. It is working but I don't understand what exactly is happening.

This is how I defined my streamcontroller -

StreamController streamController = StreamController.broadcast();

This is what I added in initState() -

streamController.stream.listen((data) {
  //call my backend api
});

Based on some action, I am calling this -

streamController.add(someData);

I don't understand what is being passed while listening. I haven't defined data anywhere. I can't leave it null or empty. Where is it being used??

While adding also, what data am I passing? If I need some data while calling my backend api. How do I pass it? And do I always need to listen to my stream in initState() only? I am unable to add it anywhere else. Why is that?

Upvotes: 1

Views: 110

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657937

data is the payload that is passed to you every time the stream emits an event.

(data) {
  //call my backend api
}

is a function that you pass to

streamController.stream.listen(...);

and this function is called every time the stream receives an event.

Just use

(data) {
  print('received data: $data);
}

and it should be clear.

Upvotes: 1

Related Questions