Summary - Platform channel
- Flutter course
- Advanced
- Lesson 50/69
- 4 min
Combine MethodChannel and EventChannel to read battery level.
Battery status
A battery status app combines MethodChannel and EventChannel. On launch, the current battery level is obtained with invokeMethod('getBatteryLevel'), then battery changes are continuously listened to via EventChannel.receiveBroadcastStream. Together these two mechanisms provide both the initial state and continuous updates.
final level = await channel.invokeMethod('getBatteryLevel');
eventChannel.receiveBroadcastStream().listen((event) {
print(event);
});Practice Write a battery status flow
Create a MethodChannel and an EventChannel. First await the current level with invokeMethod('getBatteryLevel') and print it. Then listen to the EventChannel's receiveBroadcastStream and print the incoming event. Wait 10 milliseconds.
Starter code
class MethodChannel {
final String name;
MethodChannel(this.name);
Future<int> invokeMethod(String method) async => 80;
}
class EventChannel {
final String name;
EventChannel(this.name);
Stream<dynamic> receiveBroadcastStream() => Stream.value(75);
}
void main() async {
// MethodChannel ve EventChannel oluştur
// anlık seviye al ve yazdır
// EventChannel akışını dinle ve yazdır
}Sample solution
class MethodChannel {
final String name;
MethodChannel(this.name);
Future<int> invokeMethod(String method) async => 80;
}
class EventChannel {
final String name;
EventChannel(this.name);
Stream<dynamic> receiveBroadcastStream() => Stream.value(75);
}
void main() async {
const channel = MethodChannel('samples.flutter.dev/battery');
const eventChannel = EventChannel('samples.flutter.dev/batteryStream');
final level = await channel.invokeMethod('getBatteryLevel');
print(level);
eventChannel.receiveBroadcastStream().listen((event) {
print(event);
});
await Future.delayed(Duration(milliseconds: 10));
}Expected output
80 75
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How are MethodChannel and EventChannel used together in a battery status app?
- They are the same channel
- Only MethodChannel is used
- MethodChannel gives the current level, EventChannel gives changes Correct answer
- EventChannel gives the current level
Explanation: MethodChannel reads the current battery level once; EventChannel emits continuously as the battery changes. They are used together.
2 Get the current level
final level = await channel.____('getBatteryLevel');
final level = await channel.invokeMethod('getBatteryLevel');
Explanation: To get the current battery level you call invokeMethod and pass the 'getBatteryLevel' method name.
3 Battery status parts
| Term | Meaning |
|---|---|
MethodChannel |
Current level |
EventChannel |
Continuous change |
invokeMethod |
One-time call |
receiveBroadcastStream |
Produces a stream |