Reputation: 5381
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
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