getBatteryLevel method

  1. @override
Future<double> getBatteryLevel()
override

Retrieves the battery level of the device.

This method makes use of the getBattery function (assumed to be defined elsewhere) which fetches the battery information. It then retrieves the battery level property from the returned battery manager.

The method will attempt to convert the JavaScript promise returned by getBattery into a Dart future. If any step in this process fails, an exception will be thrown with a message indicating failure to fetch the battery level.

@return A Future that resolves to a double value representing the battery level. The value is between 0.0 (fully discharged) to 1.0 (fully charged).

@throws Exception if there's a failure in fetching the battery level or converting the JavaScript promise.

Implementation

@override
Future<double> getBatteryLevel() async {
  try {
    // converts a javascript promise to a dart future
    final Future<BatteryManager> batteryFuture =
        promiseToFuture<BatteryManager>(getBattery());

    final BatteryManager batteryManager = await batteryFuture;

    final double level = getProperty(batteryManager, 'level');
    return level;
  } catch (e) {
    throw Exception('Failed to fetch battery level');
  }
}