Flutter:设备唯一id生成,存储,

1、需要用到以下插件

bash 复制代码
  # 设备信息
  device_info_plus: ^9.1.2
  uuid: ^4.5.2
  flutter_secure_storage: ^9.2.4

2、封装

dart 复制代码
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:uuid/uuid.dart';

/// 设备唯一 ID 服务
/// 
/// 使用方式:
/// ```dart
/// // 1. 在 Global.init() 中初始化
/// await DeviceId.init();
/// 
/// // 2. 在任何地方获取设备 ID
/// String deviceId = DeviceId.get();
/// ```
/// 
/// 特点:
/// - 使用 FlutterSecureStorage 存储,iOS 存储在 Keychain,Android 存储在 Keystore
/// - 即使卸载重装 App,设备 ID 依然保持不变
/// - 使用 UUID v4 生成,保证全球唯一性
class DeviceId {
  // 单例实现
  static final DeviceId _instance = DeviceId._internal();
  factory DeviceId() => _instance;
  DeviceId._internal();

  // Flutter 安全存储,用于 Keychain/Keystore
  static const FlutterSecureStorage _storage = FlutterSecureStorage();

  // UUID 生成器
  static const _uuidGen = Uuid();

  // 设备唯一 ID 的存储 key
  static const _keyDeviceId = 'ayi_device_unique_id';

  // 缓存的设备 ID
  static String? _deviceId;

  /// 初始化设备 ID
  /// 
  /// 应在 App 启动时调用一次
  static Future<void> init() async {
    await _loadOrGenerateDeviceId();
  }

  /// 加载或生成设备 ID
  static Future<void> _loadOrGenerateDeviceId() async {
    // 1. 先尝试从安全存储读取
    _deviceId = await _storage.read(key: _keyDeviceId);

    // 2. 如果读不到(首次安装或被清除)
    if (_deviceId == null || _deviceId!.isEmpty) {
      // 3. 生成新的 UUID v4
      _deviceId = _uuidGen.v4();

      // 4. 保存到安全存储(Keychain/Keystore)
      // 即使卸载重装,数据依然存在
      await _storage.write(key: _keyDeviceId, value: _deviceId);
    }
  }

  /// 获取设备唯一 ID
  /// 
  /// 返回示例:'550e8400-e29b-41d4-a716-446655440000'
  /// 
  /// 注意:使用前必须先调用 `DeviceId.init()`
  static String get() {
    if (_deviceId == null || _deviceId!.isEmpty) {
      throw StateError(
        'DeviceId 未初始化!请在 Global.init() 中调用 DeviceId.init()',
      );
    }
    return _deviceId!;
  }

  /// 重置设备 ID(谨慎使用)
  /// 
  /// 生成新的设备 ID 并保存
  /// 通常用于测试或用户主动解绑设备的场景
  static Future<void> reset() async {
    // 生成新的 UUID
    _deviceId = _uuidGen.v4();

    // 保存到安全存储
    await _storage.write(key: _keyDeviceId, value: _deviceId);
  }

  /// 清除设备 ID(谨慎使用)
  /// 
  /// 从安全存储中删除设备 ID
  /// 下次调用 `init()` 时会生成新的 ID
  static Future<void> clear() async {
    await _storage.delete(key: _keyDeviceId);
    _deviceId = null;
  }
}

3、页面中使用

dart 复制代码
String deviceId = DeviceId.get();
相关推荐
恋猫de小郭21 小时前
Android R8 为什么可以让 Kotlin 协程提速 2 倍?
android·前端·flutter
杉氧21 小时前
弹性滚动的奥秘:在 Flutter 中使用 CustomScrollView 与 Sliver 打造极致流畅列表
android·前端·flutter
张风捷特烈1 天前
Flutter UI 解耦 - 天下大势,合久必分, 分久必合
android·前端·flutter
Patrick_Wilson1 天前
从 React 到 Flutter:写给前端的一张跨端知识地图
前端·flutter·react.js
奎叔2 天前
Flutter 分层架构:从页面堆叠到可演进的业务边界
flutter
奎叔2 天前
Flutter 客户端 Trace 与稳定性治理:从链路追踪到灰度、降级和复盘
flutter
GitLqr2 天前
别被“Flutter 传感器延迟 150ms”带偏了:这可能只是你的实现方式错了
flutter·架构·kotlin
杉氧2 天前
Flutter 像素级还原实战:用 CustomPaint 与 Bezier 曲线手绘精致图针
android·前端·flutter
山璞3 天前
将一个 Flutter 项目转为用 ArkUI-X 框架实现(4)
flutter·harmonyos
GitLqr3 天前
彻底搞懂 Dart Stream:从底层原理到 Flutter 实战与面试题集
flutter·响应式编程·dart