Skip to content

Instantly share code, notes, and snippets.

@matifdeveloper
Created January 30, 2024 07:47
Show Gist options
  • Save matifdeveloper/aed1ed594a7ba0f9855e6ff72d771bad to your computer and use it in GitHub Desktop.
Save matifdeveloper/aed1ed594a7ba0f9855e6ff72d771bad to your computer and use it in GitHub Desktop.
Stream controller
import 'dart:async';
void main() {
// Create a StreamController with integers
StreamController<int> streamController = StreamController<int>();
// Create a stream from the controller
Stream<int> stream = streamController.stream;
// Add a listener to the stream
StreamSubscription<int> subscription = stream.listen(
(int data) {
print("Received data: $data");
},
onDone: () {
print("Stream closed");
},
onError: (error) {
print("Error: $error");
},
cancelOnError: false, // Set to true if you want to cancel on error
);
// Add some data to the stream
streamController.add(1);
Future.delayed(Duration(seconds: 1), (){
streamController.add(2);
});
Future.delayed(Duration(seconds: 2), (){
streamController.add(3);
});
Future.delayed(Duration(seconds: 3), (){
// Close the stream when done
streamController.close();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment