Flutter跨平台UUID生成工具uuid_test鸿蒙化使用指南

1. 插件介绍

uuid_test 是一个专为 OpenHarmony 平台适配的 Flutter UUID 生成工具,基于 pub.dev 上的 uuid 4.1.0 版本进行定制化修改。该插件提供了多种 UUID 版本的生成能力,满足不同场景下的唯一标识需求。

核心功能特点:

  • 支持多种 UUID 版本:V1(基于时间)、V4(随机)、V5(基于命名空间)、V6、V7、V8
  • 提供丰富的配置选项,支持自定义时间戳、随机数生成器、命名空间等
  • 兼容 OpenHarmony API 9+ 版本
  • 支持直接生成字符串格式和字节数组格式的 UUID
  • 提供 UUID 验证功能

应用场景:

  • 设备唯一标识生成
  • 数据库记录主键
  • 分布式系统节点标识
  • 日志跟踪和事件关联
  • 安全令牌和会话标识

2. 环境要求

在开始使用前,请确保您的开发环境满足以下要求:

  • OpenHarmony SDK:API 9+ 版本
  • Flutter SDK:3.0+ 版本
  • Dart SDK:2.19.6+ 版本
  • DevEco Studio:最新稳定版本

3. 包的引入

由于这是一个针对 OpenHarmony 平台定制修改的版本,需要通过 Git 形式引入:

3.1 修改 pubspec.yaml

在您的 Flutter 项目中,修改 pubspec.yaml 文件,添加以下依赖配置:

yaml 复制代码
dependencies:
  flutter:
    sdk: flutter
  
  uuid:
    git:
      url: "https://atomgit.com/flutter/plugins"
      path: "packages/uuid/uuid"

3.2 安装依赖

运行以下命令安装依赖:

bash 复制代码
flutter pub get

3.3 OpenHarmony 平台配置

确保您的 OpenHarmony 项目配置正确,特别是:

  1. EntryAbility.ets 文件中已正确初始化 Flutter 引擎:
typescript 复制代码
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { GeneratedPluginRegistrant } from '@register.generatedplugin';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
    GeneratedPluginRegistrant.register(this);
  }
  
  onWindowStageCreate(windowStage: window.WindowStage) {
    windowStage.loadContent('pages/Index', (err, data) => {
      // 页面加载逻辑
    });
  }
}
  1. module.json5 中已正确配置:
json5 复制代码
{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "Flutter UUID Test Entry",
    "mainElement": "EntryAbility",
    "deviceTypes": ["phone", "tablet"],
    "deliveryWithInstall": true,
    "installationFree": false,
    "pages": ["pages/Index"],
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "description": "Main Entry Ability",
        "icon": "$media:icon",
        "label": "UUID Test",
        "startWindowIcon": "$media:icon",
        "startWindowBackground": "$color:start_window_background",
        "skills": [
          {
            "entities": ["entity.system.home"],
            "actions": ["action.system.home"]
          }
        ]
      }
    ]
  }
}

4. API 调用示例

4.1 基本用法

首先导入 uuid 包:

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

创建 Uuid 实例:

dart 复制代码
var uuid = const Uuid();

4.2 生成 UUID V1(基于时间)

UUID V1 基于时间戳和节点 ID 生成,适用于需要按时间排序的场景:

dart 复制代码
// 基本用法
String v1Uuid = uuid.v1();
print('V1 UUID: $v1Uuid');

// 自定义时间戳
int customTime = DateTime.now().millisecondsSinceEpoch;
String v1UuidWithTime = uuid.v1(options: {'mSecs': customTime});
print('V1 UUID with custom time: $v1UuidWithTime');

// 生成字节数组
Uint8List v1Buffer = Uint8List(16);
uuid.v1buffer(v1Buffer, options: {'mSecs': customTime});
String parsedUuid = Uuid.unparse(v1Buffer);
print('Parsed V1 UUID from buffer: $parsedUuid');

4.3 生成 UUID V4(随机)

UUID V4 基于随机数生成,是最常用的版本:

dart 复制代码
// 基本用法
String v4Uuid = uuid.v4();
print('V4 UUID: $v4Uuid');

// 自定义随机数源
String v4UuidWithCustomRng = uuid.v4(options: {
  'random': [
    0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea,
    0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36
  ]
});
print('V4 UUID with custom random: $v4UuidWithCustomRng');

// 验证 UUID 唯一性
Set<String> uuids = {};
bool hasDuplicate = false;
for (int i = 0; i < 1000; i++) {
  String newUuid = uuid.v4();
  if (uuids.contains(newUuid)) {
    hasDuplicate = true;
    break;
  }
  uuids.add(newUuid);
}
print('Has duplicate UUIDs: $hasDuplicate');

4.4 生成 UUID V5(基于命名空间和名称)

UUID V5 基于命名空间和名称的哈希值生成,适用于需要确定性 UUID 的场景:

dart 复制代码
// 使用预定义命名空间
String v5Uuid = uuid.v5(Uuid.NAMESPACE_URL, 'www.example.com');
print('V5 UUID for example.com: $v5Uuid');

// 使用自定义命名空间
String customNamespace = '12345678-1234-5678-1234-567812345678';
String v5UuidCustomNs = uuid.v5(customNamespace, 'my-resource');
print('V5 UUID with custom namespace: $v5UuidCustomNs');

// 生成字节数组
Uint8List v5Buffer = Uint8List(16);
uuid.v5buffer(Uuid.NAMESPACE_URL, 'www.example.com', v5Buffer);
String parsedV5Uuid = Uuid.unparse(v5Buffer);
print('Parsed V5 UUID from buffer: $parsedV5Uuid');

4.5 生成 UUID V6、V7、V8

这些是较新的 UUID 版本,提供了不同的特性:

dart 复制代码
// UUID V6
String v6Uuid = uuid.v6();
print('V6 UUID: $v6Uuid');

// UUID V7
String v7Uuid = uuid.v7();
print('V7 UUID: $v7Uuid');

// UUID V8
String v8Uuid = uuid.v8();
print('V8 UUID: $v8Uuid');

4.6 UUID 验证

您可以使用 isValidUUID 方法验证 UUID 格式:

dart 复制代码
String validUuid = '12345678-1234-5678-1234-567812345678';
String invalidUuid = 'invalid-uuid';

bool isValid = Uuid.isValidUUID(fromString: validUuid);
bool isInvalid = Uuid.isValidUUID(fromString: invalidUuid);

print('Valid UUID check: $isValid');
print('Invalid UUID check: $isInvalid');

// 严格模式验证
bool isValidStrict = Uuid.isValidUUID(
  fromString: validUuid,
  validationMode: ValidationMode.strictRFC4122
);
print('Strict RFC4122 validation: $isValidStrict');

5. 完整示例应用

以下是一个在鸿蒙平台上使用 uuid 包的完整示例页面:

dart 复制代码
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';

class UuidGeneratorPage extends StatefulWidget {
  const UuidGeneratorPage({Key? key}) : super(key: key);

  @override
  State<UuidGeneratorPage> createState() => _UuidGeneratorPageState();
}

class _UuidGeneratorPageState extends State<UuidGeneratorPage> {
  final uuid = const Uuid();
  String v1Result = '';
  String v4Result = '';
  String v5Result = '';
  String v7Result = '';

  void generateV1() {
    setState(() {
      v1Result = uuid.v1();
    });
  }

  void generateV4() {
    setState(() {
      v4Result = uuid.v4();
    });
  }

  void generateV5() {
    setState(() {
      v5Result = uuid.v5(Uuid.NAMESPACE_URL, 'www.openharmony.cn');
    });
  }

  void generateV7() {
    setState(() {
      v7Result = uuid.v7();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('UUID Generator - OpenHarmony'),
        backgroundColor: Colors.blue,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _buildUuidCard('UUID V1 (时间)', v1Result, generateV1),
            const SizedBox(height: 16),
            _buildUuidCard('UUID V4 (随机)', v4Result, generateV4),
            const SizedBox(height: 16),
            _buildUuidCard('UUID V5 (命名空间)', v5Result, generateV5),
            const SizedBox(height: 16),
            _buildUuidCard('UUID V7 (时间有序)', v7Result, generateV7),
          ],
        ),
      ),
    );
  }

  Widget _buildUuidCard(String title, String result, VoidCallback onGenerate) {
    return Card(
      elevation: 4,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Text(
              result.isEmpty ? '点击按钮生成' : result,
              style: TextStyle(
                fontSize: 14,
                color: result.isEmpty ? Colors.grey : Colors.black,
                fontFamily: 'monospace',
              ),
              textAlign: TextAlign.justify,
            ),
            const SizedBox(height: 12),
            ElevatedButton(
              onPressed: onGenerate,
              child: const Text('生成 UUID'),
            ),
          ],
        ),
      ),
    );
  }
}

6. 注意事项

  1. UUID 唯一性

    • UUID V4 基于随机数生成,理论上存在极低的重复概率
    • 对于需要绝对唯一性的场景,建议结合其他标识信息使用
  2. 性能考虑

    • 随机 UUID (V4) 生成速度最快
    • 基于时间的 UUID (V1) 生成需要访问系统时钟
    • 基于命名空间的 UUID (V5) 生成需要计算哈希值
  3. 鸿蒙平台适配

    • 确保使用 API 9+ 版本的 OpenHarmony SDK
    • 遵循 OpenHarmony 的权限管理要求
    • 在 UI 线程外执行大量 UUID 生成操作,避免阻塞界面

7. 总结

uuid_test 插件为 OpenHarmony 平台提供了完整的 UUID 生成解决方案,支持多种 UUID 版本,满足不同场景的需求。通过简单的 API 调用,开发者可以轻松生成各种类型的 UUID,并集成到自己的应用中。

如果您在使用过程中遇到问题或有改进建议,欢迎加入开源鸿蒙跨平台社区,与其他开发者交流经验:

欢迎加入开源鸿蒙跨平台社区: https://openharmonycrossplatform.csdn.net

相关推荐
未来猫咪花8 小时前
Everything is ViewModel:让状态管理回到对象世界
android·flutter·ios
贾伟康8 小时前
【时光清单|05】HarmonyOS ArkTS 倒计时卡片实战:适配 2x2、2x4 与 4x4 多尺寸
harmonyos·arkts·arkui·服务卡片·formextensionability
Flutter OH9 小时前
Flutter OH 日志抓取与过滤指南
flutter
️学习的小王9 小时前
Git项目提交忽略文件怎么做?以Python项目为例,详解.gitignore
git·python·elasticsearch
Flutter OH9 小时前
Flutter OH 内存与 GPU 问题定位指南
flutter
Elasticsearch9 小时前
安装 Elasticsearch
elasticsearch
小雨青年9 小时前
【HarmonyOS 7 悬浮页签深度实战】07 折叠屏、平板与宽窗口的布局适配
华为·harmonyos
南梦浅9 小时前
GitLab 企业级实操手册:从基础命令到生产环境安全回退(revert 完整流程)
大数据·elasticsearch·搜索引擎
Flutter OH10 小时前
Flutter OH 多设备适配问题定位指南
flutter
律宏阔11 小时前
Flutter Hooks 与 flutter_map_animations 冲突:第二次地图动画报错的解决方案
flutter