EventChannel
- Flutter course
- Advanced
- Lesson 49/69
- 4 min
Stream native events with EventChannel.
What is EventChannel?
EventChannel is a channel that provides a continuous event stream from the native side to Dart. It is used for continuously updating data such as sensor data or battery level changes. The receiveBroadcastStream method returns a Stream and is listened to with listen.
const eventChannel = EventChannel('samples.flutter.dev/sensor');
eventChannel.receiveBroadcastStream().listen((event) {
print(event);
});receiveBroadcastStream
The receiveBroadcastStream method turns an EventChannel into a stream. This stream emits every event from the native side. The listener is registered with listen, and the callback is called when an event arrives. The stream can be canceled with cancel.
final stream = eventChannel.receiveBroadcastStream();
final sub = stream.listen((event) {
print(event);
});Practice Listen to an EventChannel
Create an EventChannel, get the stream with receiveBroadcastStream and listen with listen, printing the incoming event. Wait 10 milliseconds.
Starter code
class EventChannel {
final String name;
EventChannel(this.name);
Stream<dynamic> receiveBroadcastStream() => Stream.value(42);
}
void main() async {
// EventChannel oluştur
// akışı al ve dinle
}Sample solution
class EventChannel {
final String name;
EventChannel(this.name);
Stream<dynamic> receiveBroadcastStream() => Stream.value(42);
}
void main() async {
const eventChannel = EventChannel('samples.flutter.dev/sensor');
eventChannel.receiveBroadcastStream().listen((event) {
print(event);
});
await Future.delayed(Duration(milliseconds: 10));
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is EventChannel preferred?
- Only for error handling
- To save to the database
- For a one-time method call
- For a continuous event stream Correct answer
Explanation: EventChannel is preferred for continuous event streams; for one-time calls you use MethodChannel.
2 Get the stream and listen
eventChannel.____().listen((event) {
print(event);
});
eventChannel.receiveBroadcastStream().listen((event) {
print(event);
});
Explanation: To turn an EventChannel into a stream you call the receiveBroadcastStream method; it is called with parentheses and listened to with .listen.
3 EventChannel parts
| Term | Meaning |
|---|---|
EventChannel |
Event stream channel |
receiveBroadcastStream |
Produces a stream |
listen |
Listens to events |
stream |
Continuous data flow |