getDeviceIdentifier static method

Future<String> getDeviceIdentifier()

Implementation

static Future<String> getDeviceIdentifier() async {
  String deviceIdentifier = 'unknown';
  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

  try {
    if (kIsWeb) {
      // For web, you might combine several properties to create a "fingerprint"
      // as there's no single persistent ID like on mobile.
      WebBrowserInfo webInfo = await deviceInfo.webBrowserInfo;
      deviceIdentifier =
          '${webInfo.vendor ?? ''}-${webInfo.userAgent ?? ''}-${webInfo.hardwareConcurrency.toString()}';
    } else if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      // androidId is generally considered the most stable for Android,
      // but it can change on factory reset or if certain conditions are met (e.g., app reinstall on Android 8+ after OTA).
      deviceIdentifier = androidInfo.id;
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      // identifierForVendor is unique to the app's vendor and remains consistent
      // for all apps from the same vendor on that device. It changes if all apps
      // from that vendor are uninstalled and then reinstalled.
      deviceIdentifier = iosInfo.identifierForVendor ?? 'unknown_ios_id';
    } else if (Platform.isLinux) {
      LinuxDeviceInfo linuxInfo = await deviceInfo.linuxInfo;
      deviceIdentifier = linuxInfo.machineId ?? 'unknown_linux_id';
    } else if (Platform.isWindows) {
      WindowsDeviceInfo windowsInfo = await deviceInfo.windowsInfo;
      deviceIdentifier = windowsInfo
          .computerName; // Or another property that suits your needs
    } else if (Platform.isMacOS) {
      MacOsDeviceInfo macOsInfo = await deviceInfo.macOsInfo;
      deviceIdentifier =
          macOsInfo.systemGUID ?? 'unknown_macos_id'; // System GUID
    }
  } catch (e) {
    print('Failed to get device info: $e');
    deviceIdentifier = 'error_getting_id';
  }

  return deviceIdentifier;
}