0
0
Fluttermobile~10 mins

Platform channels (MethodChannel) in Flutter - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a MethodChannel with the name 'samples.flutter.dev/battery'.

Flutter
static const platform = MethodChannel('[1]');
Drag options to blanks, or click blank then click option'
Asamples.flutter.battery
Bflutter.dev/battery
Csamples.flutter.dev/battery
Dbattery.flutter.dev
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong or incomplete channel name.
Missing parts of the channel string.
2fill in blank
medium

Complete the code to invoke the native method 'getBatteryLevel' asynchronously.

Flutter
final int batteryLevel = await platform.[1]('getBatteryLevel');
Drag options to blanks, or click blank then click option'
AexecuteMethod
BsendMethod
CcallMethod
DinvokeMethod
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent method like callMethod.
Forgetting to await the asynchronous call.
3fill in blank
hard

Fix the error in the code by completing the catch block to handle PlatformException.

Flutter
try {
  final int batteryLevel = await platform.invokeMethod('getBatteryLevel');
} on [1] catch (e) {
  print('Failed to get battery level: $e');
}
Drag options to blanks, or click blank then click option'
APlatformException
BException
CError
DMethodChannelException
Attempts:
3 left
💡 Hint
Common Mistakes
Catching generic Exception instead of PlatformException.
Using a non-existent exception class.
4fill in blank
hard

Fill both blanks to send an argument map with key 'charging' and value true to native code.

Flutter
final bool isCharging = await platform.invokeMethod('isCharging', [1]);
Drag options to blanks, or click blank then click option'
A{'charging': false}
B{'charging': true}
C['charging', true]
Dtrue
Attempts:
3 left
💡 Hint
Common Mistakes
Sending a list instead of a map.
Sending just a boolean without a key.
5fill in blank
hard

Fill all three blanks to define a MethodChannel, invoke 'getBatteryLevel', and handle exceptions properly.

Flutter
static const platform = MethodChannel('[1]');

Future<int> getBatteryLevel() async {
  try {
    final int batteryLevel = await platform.[2]('getBatteryLevel');
    return batteryLevel;
  } on [3] catch (e) {
    return -1;
  }
}
Drag options to blanks, or click blank then click option'
Asamples.flutter.dev/battery
BinvokeMethod
CPlatformException
DcallMethod
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong channel name or method name.
Catching wrong exception type.
Not awaiting the method call.