Complete the code to create a MethodChannel with the name 'samples.flutter.dev/battery'.
static const platform = MethodChannel('[1]');
The MethodChannel name must match exactly between Flutter and native code. Here, 'samples.flutter.dev/battery' is the correct channel name.
Complete the code to invoke the native method 'getBatteryLevel' asynchronously.
final int batteryLevel = await platform.[1]('getBatteryLevel');
The correct method to call native code asynchronously is invokeMethod.
Fix the error in the code by completing the catch block to handle PlatformException.
try { final int batteryLevel = await platform.invokeMethod('getBatteryLevel'); } on [1] catch (e) { print('Failed to get battery level: $e'); }
The native platform errors are caught as PlatformException in Flutter.
Fill both blanks to send an argument map with key 'charging' and value true to native code.
final bool isCharging = await platform.invokeMethod('isCharging', [1]);
The argument must be a map with key 'charging' and value true to send data properly.
Fill all three blanks to define a MethodChannel, invoke 'getBatteryLevel', and handle exceptions properly.
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; } }
This code creates a MethodChannel with the correct name, calls the native method asynchronously, and catches PlatformException to handle errors.