| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- // device_info_plus 中 androidInfo.androidId 被移除,无法获取跨应用的设备唯一标识
- // 为了代码一致性,iOS 端也不使用 iosInfo.identifierForVendor
- // 统一使用 uuid.dart 来随机生成
- import 'package:shared_preferences/shared_preferences.dart';
- import 'package:uuid/uuid.dart';
- class DeviceUuid {
- static const String _uuidKey = 'device_uuid';
- static String? _cachedUuid;
- // 获取或创建 UUID
- static Future<String> getUuid() async {
- if (_cachedUuid != null) {
- return _cachedUuid!;
- }
- final prefs = await SharedPreferences.getInstance();
- String? storedUuid = prefs.getString(_uuidKey);
- if (storedUuid == null || storedUuid.isEmpty) {
- storedUuid = _generateAndStoreUuid(prefs);
- }
- _cachedUuid = storedUuid;
- return storedUuid;
- }
- // 生成并存储新的 UUID
- static String _generateAndStoreUuid(SharedPreferences prefs) {
- final newUuid = const Uuid().v4();
- prefs.setString(_uuidKey, newUuid);
- return newUuid;
- }
- // 重置 UUID(用户选择重置隐私时使用)
- static Future<String> resetUuid() async {
- final prefs = await SharedPreferences.getInstance();
- _cachedUuid = null;
- return _generateAndStoreUuid(prefs);
- }
- // 检查是否已有 UUID
- static Future<bool> hasUuid() async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.containsKey(_uuidKey);
- }
- // 清除 UUID(用户注销时)
- static Future<void> clearUuid() async {
- final prefs = await SharedPreferences.getInstance();
- await prefs.remove(_uuidKey);
- _cachedUuid = null;
- }
- }
|