Milvintsiss
Milvintsiss

Reputation: 1448

Get name of linux distribution running

Is there any way to get the linux distributionn name used to run a flutter app?

The only way I found is to parse the Platform.operatingSystemVersion string but I think if we can get it like so, Flutter team surely provide a proper way to do this?

By distribution name I mean Ubuntu, Fedora, Debian, etc.

Upvotes: 1

Views: 121

Answers (1)

Milvintsiss
Milvintsiss

Reputation: 1448

First solution:

Found that device_info_plus_linux provide what I want.

To use it (without device_info_plus):

import 'package:device_info_plus_linux/device_info_plus_linux.dart';
import 'package:device_info_plus_platform_interface/device_info_plus_platform_interface.dart' show LinuxDeviceInfo;

[...]

LinuxDeviceInfo deviceInfoLinux = await DeviceInfoLinux().linuxInfo();
print('Linux distribution: ${deviceInfoLinux.id}');

deviceInfoLinux.id will return a string containing the name of the distribution in lowercase characters (ex: 'debian', 'ubuntu', ...). If the package don't found any id it will return 'linux'.

Second solution:

In my case doing work async was not possible so I implemented my own solution:

String _getLinuxDistribution() {
  String linuxDistribution;
  try {
    final List<String> osEtc = File('/etc/os-release').readAsLinesSync();
    linuxDistribution =
        osEtc.firstWhere((element) => element.indexOf("ID=") == 0);
    if (linuxDistribution != null)
      linuxDistribution = linuxDistribution.substring(3).toLowerCase();
    else
      throw Exception;
  } catch (e) {
    try {
      final List<String> osUsr = File('/usr/lib/os-release').readAsLinesSync();
      linuxDistribution =
          osUsr.firstWhere((element) => element.indexOf("ID=") == 0);
      if (linuxDistribution != null)
        linuxDistribution = linuxDistribution.substring(3).toLowerCase();
      else
        throw Exception;
    } catch (e) {
      try {
        final List<String> lsb = File('/etc/lsb-release').readAsLinesSync();
        linuxDistribution =
            lsb.firstWhere((element) => element.indexOf("DISTRIB_ID=") == 0);
        if (linuxDistribution != null)
          linuxDistribution = linuxDistribution.substring(11).toLowerCase();
        else
          throw Exception;
      } catch (e) {
        print(_red("Error getting Linux distribution name"));
        linuxDistribution = 'linux';
      }
    }
  }
  return linuxDistribution;
}

note that the performance impact is negligable, I mesured it between 10ms and 30ms.

Upvotes: 1

Related Questions