getPowerData function

PowerData getPowerData({
  1. bool isThrowOnError = false,
})

Implementation

PowerData getPowerData({
  bool isThrowOnError = false,
}) {
  try {
    if (Dart.isLinux || Dart.isAndroid) {
      final data = (Process.runSync(
        "lspower",
        [],
      ))
          .stdout
          .toString()
          .trim()
          .split("\n")
          .map((e) {
            try {
              return e.replaceAll(RegExp("([()%])", caseSensitive: false), "");
            } catch (e) {}
            return null;
          })
          .whereType<String>()
          .toList();

      PowerData powerData = PowerData.create();
      for (var element in data) {
        final List<String> datas = element.split(" ");
        if (datas.isEmpty) {
          continue;
        }
        final Args args = Args(datas);
        String name_first = args.arguments.first;
        String name_type = (args.after(name_first) ?? "").trim();

        if (RegExp("BAT", caseSensitive: false).hasMatch(name_type)) {
          if (name_first == "+") {
            powerData["is_charging"] = true;
          } else {
            powerData["is_charging"] = false;
          }
          powerData["level"] = num.tryParse(args.after(name_type) ?? "0");
          continue;
        }
      }

      return powerData;
    }
  } catch (e) {
    if (isThrowOnError) {
      rethrow;
    }
  }

  return PowerData.create();
}