import 'dart:math'; import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; const _kDeviceIdKey = 'device_id'; /// Returns a stable device identifier persisted across app launches. /// On first call a random UUID-v4 is generated and stored in SharedPreferences. /// Follows the rule: check kIsWeb before dart:io. class DeviceId { static String? _cached; static Future get() async { if (_cached != null) return _cached!; final prefs = await SharedPreferences.getInstance(); var id = prefs.getString(_kDeviceIdKey); if (id == null || id.isEmpty) { id = _generateUuid(); await prefs.setString(_kDeviceIdKey, id); } return _cached = id; } /// Best-effort platform name for display purposes. static String get platformName { if (kIsWeb) return 'web'; // defaultTargetPlatform is safe on all platforms (no dart:io needed) switch (defaultTargetPlatform) { case TargetPlatform.windows: return 'windows'; case TargetPlatform.macOS: return 'macos'; case TargetPlatform.android: return 'android'; case TargetPlatform.iOS: return 'ios'; case TargetPlatform.linux: return 'linux'; default: return 'unknown'; } } static String _generateUuid() { final rng = Random.secure(); final bytes = List.generate(16, (_) => rng.nextInt(256)); bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4 bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-' '${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}'; } }