getDeviceId static method

Future<String> getDeviceId()

Implementation

static Future<String> getDeviceId() async {
  // 1. Return cached ID if it exists
  final cachedId = await _storage.read(key: _storageKey);
  if (cachedId != null && cachedId.isNotEmpty) {
    return cachedId;
  }

  String? deviceId;

  // 2. Try platform-specific IDs
  try {
    if (Platform.isAndroid) {
      // Use android_id package for safer access
      final androidIdPlugin = const AndroidId();
      deviceId = await androidIdPlugin.getId();
    } else if (Platform.isIOS) {
      final iosInfo = await _deviceInfo.iosInfo;
      deviceId = iosInfo.identifierForVendor; // ID unique to vendor on iOS
    }
  } catch (_) {
    // Handle potential errors, fall through to fallback
  }

  // 3. Generate and cache a UUID fallback if platform ID is unavailable
  if (deviceId == null || deviceId.isEmpty) {
    deviceId = _uuid.v4();
  }

  // Store the obtained or generated ID securely
  await _storage.write(key: _storageKey, value: deviceId);
  return deviceId;
}