Flutter鸿蒙化之深入解析Pigeon基本数据类型:primitive.dart全解

源码:https://atomgit.com/openharmony-tpc/flutter_packages/blob/master/packages/pigeon/pigeons/primitive.dart

一、基本数据类型在跨平台通信中的基础作用

基本数据类型是所有高级数据结构的基础,也是跨平台通信中最核心、最频繁使用的部分。primitive.dart文件展示了Pigeon对Dart基本数据类型的全面支持,这是构建高效、可靠跨平台通信的基石。

二、文件结构与设计理念

2.1 基础信息与重要性

dart 复制代码
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:pigeon/pigeon.dart';

文件特点

  • 基本数据类型全覆盖:涵盖数值、布尔、字符串、集合等所有基本类型
  • 对称性设计:同时定义@HostApi和@FlutterApi,展示双向通信
  • 实战导向:包含常见但易忽略的类型,如Int32List、可空集合

2.2 主机API接口定义

dart 复制代码
@HostApi()
abstract class PrimitiveHostApi {
  int anInt(int value);
  bool aBool(bool value);
  String aString(String value);
  double aDouble(double value);
  // ignore: always_specify_types, strict_raw_type
  Map aMap(Map value);
  // ignore: always_specify_types, strict_raw_type
  List aList(List value);
  Int32List anInt32List(Int32List value);
  List<bool?> aBoolList(List<bool?> value);
  Map<String?, int?> aStringIntMap(Map<String?, int?> value);
}

接口设计亮点

2.3 Flutter API对称定义

dart 复制代码
@FlutterApi()
abstract class PrimitiveFlutterApi {
  // 与PrimitiveHostApi完全对称的方法定义
  int anInt(int value);
  bool aBool(bool value);
  // ... 其他方法相同
}

对称设计的重要性

三、基本数据类型的跨平台映射

3.1 完整类型映射表

3.2 特殊类型深度解析

3.2.1 Int32List类型分析
dart 复制代码
Int32List anInt32List(Int32List value);

Int32List的特殊性

  1. 性能优势:连续的32位整数数组,内存布局紧凑
  2. 二进制友好:适合直接序列化为二进制格式
  3. 平台差异:不同平台可能有不同的优化实现

鸿蒙端Int32List处理

typescript 复制代码
// 鸿蒙ArkTS中的Int32Array处理
export class Int32ListHandler {
  
  // Dart的Int32List转换为鸿蒙的Int32Array
  static fromDartInt32List(dartList: any): Int32Array {
    if (!dartList || !dartList.data) {
      return new Int32Array(0);
    }
    
    // 假设dartList.data是基础数组
    return Int32Array.from(dartList.data);
  }
  
  // 鸿蒙的Int32Array转换为Dart格式
  static toDartInt32List(array: Int32Array): any {
    return {
      type: 'Int32List',
      data: Array.from(array),
      length: array.length
    };
  }
  
  // 高效的二进制序列化
  static serializeToBinary(array: Int32Array): Uint8Array {
    const buffer = new ArrayBuffer(array.length * 4); // 每个int32占4字节
    const view = new DataView(buffer);
    
    for (let i = 0; i < array.length; i++) {
      view.setInt32(i * 4, array[i], true); // little-endian
    }
    
    return new Uint8Array(buffer);
  }
}
3.2.2 可空集合类型分析
dart 复制代码
List<bool?> aBoolList(List<bool?> value);
Map<String?, int?> aStringIntMap(Map<String?, int?> value);

可空集合的复杂性

3.3 动态类型的设计考虑

dart 复制代码
// ignore: always_specify_types, strict_raw_type
Map aMap(Map value);
// ignore: always_specify_types, strict_raw_type
List aList(List value);

动态类型的实用场景

  1. 快速原型:开发初期不需要严格类型定义
  2. 灵活数据:处理结构不确定的第三方数据
  3. 性能优先:避免类型检查的开销
  4. 向后兼容:支持旧版本的非类型安全数据

动态类型的风险与缓解

四、在鸿蒙项目中的完整实现

4.1 代码生成命令

bash 复制代码
# 生成基本数据类型支持的代码
flutter pub run pigeon \
  --input pigeons/primitive.dart \
  --dart_out lib/primitive_api.dart \
  --arkts_out harmony/primitive_api.ts \
  --java_out android/app/src/main/java/com/example/PrimitiveApi.java \
  --java_package "com.example" \
  --objc_header_out ios/Runner/PrimitiveApi.h \
  --objc_source_out ios/Runner/PrimitiveApi.m \
  --cpp_header_out windows/runner/PrimitiveApi.h \
  --cpp_source_out windows/runner/PrimitiveApi.cpp

生成的鸿蒙ArkTS接口

typescript 复制代码
// harmony/primitive_api.ts (生成的部分)
export interface PrimitiveHostApi {
  anInt(value: number): Promise<number>;
  aBool(value: boolean): Promise<boolean>;
  aString(value: string): Promise<string>;
  aDouble(value: number): Promise<number>;
  aMap(value: Record<string, any>): Promise<Record<string, any>>;
  aList(value: Array<any>): Promise<Array<any>>;
  anInt32List(value: Int32Array): Promise<Int32Array>;
  aBoolList(value: Array<boolean | null>): Promise<Array<boolean | null>>;
  aStringIntMap(value: Record<string | null, number | null>): 
    Promise<Record<string | null, number | null>>;
}

export interface PrimitiveFlutterApi {
  anInt(value: number): number;
  aBool(value: boolean): boolean;
  aString(value: string): string;
  aDouble(value: number): number;
  aMap(value: Record<string, any>): Record<string, any>;
  aList(value: Array<any>): Array<any>;
  anInt32List(value: Int32Array): Int32Array;
  aBoolList(value: Array<boolean | null>): Array<boolean | null>;
  aStringIntMap(value: Record<string | null, number | null>): 
    Record<string | null, number | null>;
}

4.2 鸿蒙端实现

typescript 复制代码
// harmony/primitive_api_impl.ets
import {
  PrimitiveHostApi,
  PrimitiveFlutterApi
} from './primitive_api';

/**
 * 基本数据类型主机API实现
 */
export class PrimitiveHostApiImpl implements PrimitiveHostApi {
  
  /**
   * 整型处理
   */
  async anInt(value: number): Promise<number> {
    console.debug('接收到整数:', value);
    
    // 验证整数范围
    if (!Number.isInteger(value)) {
      throw new Error('必须是整数');
    }
    
    if (value < -2147483648 || value > 2147483647) {
      console.warn('整数超出32位范围,可能损失精度');
    }
    
    // 执行操作(示例:平方)
    const result = value * value;
    
    // 模拟异步处理
    await this._simulateProcessing();
    
    return result;
  }
  
  /**
   * 布尔值处理
   */
  async aBool(value: boolean): Promise<boolean> {
    console.debug('接收到布尔值:', value);
    
    // 布尔值验证
    if (typeof value !== 'boolean') {
      throw new Error('必须是布尔值');
    }
    
    // 执行操作(示例:取反)
    const result = !value;
    
    await this._simulateProcessing();
    
    return result;
  }
  
  /**
   * 字符串处理
   */
  async aString(value: string): Promise<string> {
    console.debug('接收到字符串:', value.substring(0, 50));
    
    // 字符串验证
    if (typeof value !== 'string') {
      throw new Error('必须是字符串');
    }
    
    // 检查字符串长度
    if (value.length > 10000) {
      console.warn('字符串过长,可能影响性能');
    }
    
    // 执行操作(示例:反转)
    const result = value.split('').reverse().join('');
    
    await this._simulateProcessing();
    
    return result;
  }
  
  /**
   * 双精度浮点数处理
   */
  async aDouble(value: number): Promise<number> {
    console.debug('接收到浮点数:', value);
    
    // 浮点数验证
    if (typeof value !== 'number') {
      throw new Error('必须是数字');
    }
    
    if (!Number.isFinite(value)) {
      throw new Error('必须是有限数字');
    }
    
    // 执行操作(示例:平方根)
    const result = Math.sqrt(Math.abs(value));
    
    await this._simulateProcessing();
    
    return result;
  }
  
  /**
   * 动态Map处理
   */
  async aMap(value: Record<string, any>): Promise<Record<string, any>> {
    console.debug('接收到Map,键数量:', Object.keys(value).length);
    
    // Map验证
    if (typeof value !== 'object' || value === null) {
      throw new Error('必须是对象');
    }
    
    // 执行操作(示例:添加元数据)
    const result = {
      ...value,
      '_processed': true,
      '_timestamp': Date.now(),
      '_keyCount': Object.keys(value).length
    };
    
    await this._simulateProcessing();
    
    return result;
  }
  
  /**
   * 动态List处理
   */
  async aList(value: Array<any>): Promise<Array<any>> {
    console.debug('接收到List,长度:', value.length);
    
    // List验证
    if (!Array.isArray(value)) {
      throw new Error('必须是数组');
    }
    
    // 执行操作(示例:过滤和映射)
    const result = value
      .filter(item => item !== null && item !== undefined)
      .map((item, index) => ({
        index,
        value: item,
        type: typeof item
      }));
    
    await this._simulateProcessing();
    
    return result;
  }
  
  /**
   * Int32List处理
   */
  async anInt32List(value: Int32Array): Promise<Int32Array> {
    console.debug('接收到Int32List,长度:', value.length);
    
    // Int32Array验证
    if (!(value instanceof Int32Array)) {
      throw new Error('必须是Int32Array');
    }
    
    // 检查数据大小
    if (value.length > 1000000) {
      console.warn('Int32List过大,考虑分块处理');
    }
    
    // 执行操作(示例:每个元素加1)
    const result = new Int32Array(value.length);
    for (let i = 0; i < value.length; i++) {
      result[i] = value[i] + 1;
    }
    
    await this._simulateProcessing();
    
    return result;
  }
  
  /**
   * 可空布尔列表处理
   */
  async aBoolList(value: Array<boolean | null>): Promise<Array<boolean | null>> {
    console.debug('接收到布尔列表,长度:', value.length);
    
    // 数组验证
    if (!Array.isArray(value)) {
      throw new Error('必须是数组');
    }
    
    // 元素类型验证
    for (let i = 0; i < value.length; i++) {
      const item = value[i];
      if (item !== null && typeof item !== 'boolean') {
        throw new Error(`索引${i}: 必须是布尔值或null`);
      }
    }
    
    // 执行操作(示例:统计和转换)
    const trueCount = value.filter(item => item === true).length;
    const falseCount = value.filter(item => item === false).length;
    const nullCount = value.filter(item => item === null).length;
    
    console.debug(`统计: true=${trueCount}, false=${falseCount}, null=${nullCount}`);
    
    // 转换:true→false, false→true, null保持不变
    const result = value.map(item => {
      if (item === true) return false;
      if (item === false) return true;
      return null;
    });
    
    await this._simulateProcessing();
    
    return result;
  }
  
  /**
   * 可空字符串-整数Map处理
   */
  async aStringIntMap(
    value: Record<string | null, number | null>
  ): Promise<Record<string | null, number | null>> {
    console.debug('接收到字符串-整数Map,键数量:', Object.keys(value).length);
    
    // Map验证
    if (typeof value !== 'object' || value === null) {
      throw new Error('必须是对象');
    }
    
    // 键值类型验证
    for (const key in value) {
      if (Object.prototype.hasOwnProperty.call(value, key)) {
        const val = value[key];
        
        // 键可以为null或string
        if (key !== null && typeof key !== 'string') {
          throw new Error(`键必须是字符串或null`);
        }
        
        // 值可以为null或number
        if (val !== null && typeof val !== 'number') {
          throw new Error(`键"${key}"的值必须是数字或null`);
        }
        
        // 如果是数字,检查是否是整数
        if (val !== null && !Number.isInteger(val)) {
          console.warn(`键"${key}"的值不是整数: ${val}`);
        }
      }
    }
    
    // 执行操作(示例:值加倍,处理null)
    const result: Record<string | null, number | null> = {};
    
    for (const key in value) {
      if (Object.prototype.hasOwnProperty.call(value, key)) {
        const val = value[key];
        
        if (val === null) {
          result[key] = null;
        } else {
          result[key] = val * 2;
        }
      }
    }
    
    // 添加统计信息
    result['_stats'] = {
      keyCount: Object.keys(value).length,
      nonNullValues: Object.values(value).filter(v => v !== null).length,
      nullKeys: Object.keys(value).filter(k => k === null).length
    };
    
    await this._simulateProcessing();
    
    return result;
  }
  
  /**
   * 模拟处理延迟
   */
  private _simulateProcessing(): Promise<void> {
    return new Promise(resolve => {
      // 随机延迟50-150ms,模拟真实处理时间
      setTimeout(resolve, 50 + Math.random() * 100);
    });
  }
}

/**
 * Flutter API管理器
 */
export class PrimitiveFlutterApiManager {
  private static _instance: PrimitiveFlutterApiManager;
  private _api: PrimitiveFlutterApi | null = null;
  
  static getInstance(): PrimitiveFlutterApiManager {
    if (!PrimitiveFlutterApiManager._instance) {
      PrimitiveFlutterApiManager._instance = new PrimitiveFlutterApiManager();
    }
    return PrimitiveFlutterApiManager._instance;
  }
  
  /**
   * 注册Flutter API
   */
  registerApi(api: PrimitiveFlutterApi): void {
    this._api = api;
    console.log('PrimitiveFlutterApi已注册');
  }
  
  /**
   * 调用Flutter端的整型API
   */
  async callAnInt(value: number): Promise<number> {
    if (!this._api) {
      throw new Error('PrimitiveFlutterApi未注册');
    }
    
    try {
      const result = this._api.anInt(value);
      console.debug('Flutter端anInt返回:', result);
      return result;
    } catch (error) {
      console.error('调用Flutter端anInt失败:', error);
      throw error;
    }
  }
  
  // 其他方法的类似封装...
}

/**
 * 主机API管理器
 */
export class PrimitiveHostApiManager {
  private static _instance: PrimitiveHostApiManager;
  private _api: PrimitiveHostApiImpl | null = null;
  
  static getInstance(): PrimitiveHostApiManager {
    if (!PrimitiveHostApiManager._instance) {
      PrimitiveHostApiManager._instance = new PrimitiveHostApiManager();
    }
    return PrimitiveHostApiManager._instance;
  }
  
  /**
   * 初始化主机API
   */
  initialize(): void {
    this._api = new PrimitiveHostApiImpl();
    console.log('PrimitiveHostApi初始化完成');
  }
  
  /**
   * 注册到Flutter引擎
   */
  registerToEngine(flutterEngine: FlutterEngine): void {
    if (!this._api) {
      throw new Error('API未初始化');
    }
    
    // 注册所有方法
    const apis = [
      { name: 'PrimitiveHostApi.anInt', handler: this._handleAnInt.bind(this) },
      { name: 'PrimitiveHostApi.aBool', handler: this._handleABool.bind(this) },
      { name: 'PrimitiveHostApi.aString', handler: this._handleAString.bind(this) },
      { name: 'PrimitiveHostApi.aDouble', handler: this._handleADouble.bind(this) },
      { name: 'PrimitiveHostApi.aMap', handler: this._handleAMap.bind(this) },
      { name: 'PrimitiveHostApi.aList', handler: this._handleAList.bind(this) },
      { name: 'PrimitiveHostApi.anInt32List', handler: this._handleAnInt32List.bind(this) },
      { name: 'PrimitiveHostApi.aBoolList', handler: this._handleABoolList.bind(this) },
      { name: 'PrimitiveHostApi.aStringIntMap', handler: this._handleAStringIntMap.bind(this) }
    ];
    
    for (const api of apis) {
      const channel = `dev.flutter.pigeon.${api.name}`;
      
      flutterEngine.dartExecutor.binaryMessenger.setMessageHandler(
        channel,
        api.handler
      );
    }
    
    console.log('PrimitiveHostApi已注册到Flutter引擎');
  }
  
  private async _handleAnInt(message: Uint8Array): Promise<Uint8Array> {
    try {
      const request = this._decodeMessage(message);
      
      if (!this._api) {
        throw new Error('API未初始化');
      }
      
      const result = await this._api.anInt(request.args.value);
      
      return this._encodeResponse({
        success: true,
        result: result
      });
    } catch (error) {
      return this._encodeResponse({
        success: false,
        error: error.message
      });
    }
  }
  
  private async _handleABool(message: Uint8Array): Promise<Uint8Array> {
    try {
      const request = this._decodeMessage(message);
      
      if (!this._api) {
        throw new Error('API未初始化');
      }
      
      const result = await this._api.aBool(request.args.value);
      
      return this._encodeResponse({
        success: true,
        result: result
      });
    } catch (error) {
      return this._encodeResponse({
        success: false,
        error: error.message
      });
    }
  }
  
  private async _handleAString(message: Uint8Array): Promise<Uint8Array> {
    try {
      const request = this._decodeMessage(message);
      
      if (!this._api) {
        throw new Error('API未初始化');
      }
      
      const result = await this._api.aString(request.args.value);
      
      return this._encodeResponse({
        success: true,
        result: result
      });
    } catch (error) {
      return this._encodeResponse({
        success: false,
        error: error.message
      });
    }
  }
  
  // 其他处理方法的类似实现...
  
  private _decodeMessage(message: Uint8Array): any {
    const decoder = new TextDecoder();
    const jsonStr = decoder.decode(message);
    return JSON.parse(jsonStr);
  }
  
  private _encodeResponse(data: any): Uint8Array {
    const encoder = new TextEncoder();
    return encoder.encode(JSON.stringify(data));
  }
}

4.3 Flutter端实现

dart 复制代码
// lib/primitive_service.dart
import './primitive_api.dart';
import 'dart:typed_data';

/// 基本数据类型服务
class PrimitiveService {
  // 主机API实例
  static final PrimitiveHostApi _hostApi = PrimitiveHostApi();
  
  // Flutter API实现
  static final PrimitiveFlutterApi _flutterApi = _PrimitiveFlutterApiImpl();
  
  /// 初始化服务
  static Future<void> initialize() async {
    _setupLogging();
    _setupPerformanceMonitoring();
    
    print('PrimitiveService初始化完成');
  }
  
  /// 测试整型
  static Future<int> testInt(int value) async {
    final stopwatch = Stopwatch()..start();
    
    try {
      final result = await _hostApi.anInt(value);
      
      stopwatch.stop();
      _logPerformance('anInt', stopwatch.elapsedMilliseconds);
      
      return result;
    } catch (e, stack) {
      _logError('anInt', e, stack);
      rethrow;
    }
  }
  
  /// 测试布尔值
  static Future<bool> testBool(bool value) async {
    final stopwatch = Stopwatch()..start();
    
    try {
      final result = await _hostApi.aBool(value);
      
      stopwatch.stop();
      _logPerformance('aBool', stopwatch.elapsedMilliseconds);
      
      return result;
    } catch (e, stack) {
      _logError('aBool', e, stack);
      rethrow;
    }
  }
  
  /// 测试字符串
  static Future<String> testString(String value) async {
    final stopwatch = Stopwatch()..start();
    
    try {
      final result = await _hostApi.aString(value);
      
      stopwatch.stop();
      _logPerformance('aString', stopwatch.elapsedMilliseconds);
      
      return result;
    } catch (e, stack) {
      _logError('aString', e, stack);
      rethrow;
    }
  }
  
  /// 测试浮点数
  static Future<double> testDouble(double value) async {
    final stopwatch = Stopwatch()..start();
    
    try {
      final result = await _hostApi.aDouble(value);
      
      stopwatch.stop();
      _logPerformance('aDouble', stopwatch.elapsedMilliseconds);
      
      return result;
    } catch (e, stack) {
      _logError('aDouble', e, stack);
      rethrow;
    }
  }
  
  /// 测试动态Map
  static Future<Map<dynamic, dynamic>> testMap(Map<dynamic, dynamic> value) async {
    final stopwatch = Stopwatch()..start();
    
    try {
      final result = await _hostApi.aMap(value);
      
      stopwatch.stop();
      _logPerformance('aMap', stopwatch.elapsedMilliseconds);
      
      return result;
    } catch (e, stack) {
      _logError('aMap', e, stack);
      rethrow;
    }
  }
  
  /// 测试动态List
  static Future<List<dynamic>> testList(List<dynamic> value) async {
    final stopwatch = Stopwatch()..start();
    
    try {
      final result = await _hostApi.aList(value);
      
      stopwatch.stop();
      _logPerformance('aList', stopwatch.elapsedMilliseconds);
      
      return result;
    } catch (e, stack) {
      _logError('aList', e, stack);
      rethrow;
    }
  }
  
  /// 测试Int32List
  static Future<Int32List> testInt32List(Int32List value) async {
    final stopwatch = Stopwatch()..start();
    
    try {
      final result = await _hostApi.anInt32List(value);
      
      stopwatch.stop();
      _logPerformance('anInt32List', stopwatch.elapsedMilliseconds,
                     '长度: ${value.length}');
      
      return result;
    } catch (e, stack) {
      _logError('anInt32List', e, stack);
      rethrow;
    }
  }
  
  /// 测试可空布尔列表
  static Future<List<bool?>> testBoolList(List<bool?> value) async {
    final stopwatch = Stopwatch()..start();
    
    try {
      final result = await _hostApi.aBoolList(value);
      
      stopwatch.stop();
      _logPerformance('aBoolList', stopwatch.elapsedMilliseconds,
                     '长度: ${value.length}');
      
      return result;
    } catch (e, stack) {
      _logError('aBoolList', e, stack);
      rethrow;
    }
  }
  
  /// 测试可空字符串-整数Map
  static Future<Map<String?, int?>> testStringIntMap(Map<String?, int?> value) async {
    final stopwatch = Stopwatch()..start();
    
    try {
      final result = await _hostApi.aStringIntMap(value);
      
      stopwatch.stop();
      _logPerformance('aStringIntMap', stopwatch.elapsedMilliseconds,
                     '键数量: ${value.length}');
      
      return result;
    } catch (e, stack) {
      _logError('aStringIntMap', e, stack);
      rethrow;
    }
  }
  
  /// Flutter API实现类
  static class _PrimitiveFlutterApiImpl implements PrimitiveFlutterApi {
    @override
    int anInt(int value) {
      print('Flutter端: anInt($value)被调用');
      return value * 2;
    }
    
    @override
    bool aBool(bool value) {
      print('Flutter端: aBool($value)被调用');
      return !value;
    }
    
    @override
    String aString(String value) {
      print('Flutter端: aString("${value.substring(0, min(20, value.length))}...")被调用');
      return value.toUpperCase();
    }
    
    @override
    double aDouble(double value) {
      print('Flutter端: aDouble($value)被调用');
      return value * 1.5;
    }
    
    @override
    Map aMap(Map value) {
      print('Flutter端: aMap(键数量: ${value.length})被调用');
      
      final result = Map.from(value);
      result['_processedByFlutter'] = true;
      result['_timestamp'] = DateTime.now().millisecondsSinceEpoch;
      
      return result;
    }
    
    @override
    List aList(List value) {
      print('Flutter端: aList(长度: ${value.length})被调用');
      
      return value.reversed.toList();
    }
    
    @override
    Int32List anInt32List(Int32List value) {
      print('Flutter端: anInt32List(长度: ${value.length})被调用');
      
      final result = Int32List(value.length);
      for (var i = 0; i < value.length; i++) {
        result[i] = value[i] * 2;
      }
      
      return result;
    }
    
    @override
    List<bool?> aBoolList(List<bool?> value) {
      print('Flutter端: aBoolList(长度: ${value.length})被调用');
      
      final trueCount = value.where((item) => item == true).length;
      final falseCount = value.where((item) => item == false).length;
      final nullCount = value.where((item) => item == null).length;
      
      print('统计: true=$trueCount, false=$falseCount, null=$nullCount');
      
      return value.map((item) {
        if (item == true) return false;
        if (item == false) return true;
        return null;
      }).toList();
    }
    
    @override
    Map<String?, int?> aStringIntMap(Map<String?, int?> value) {
      print('Flutter端: aStringIntMap(键数量: ${value.length})被调用');
      
      final result = <String?, int?>{};
      
      value.forEach((key, val) {
        if (val == null) {
          result[key] = null;
        } else {
          result[key] = val + 100;
        }
      });
      
      result['_flutterProcessed'] = true;
      
      return result;
    }
  }
  
  /// 性能监控
  static void _logPerformance(String method, int duration, [String extra = '']) {
    final logEntry = {
      'method': method,
      'duration': '$duration ms',
      'extra': extra,
      'timestamp': DateTime.now().toIso8601String()
    };
    
    print('性能日志: $logEntry');
    
    // 长时间操作警告
    if (duration > 200) {
      print('警告: $method 调用耗时过长 ($duration ms)');
    }
  }
  
  static void _logError(String method, Object error, StackTrace stack) {
    final errorLog = {
      'method': method,
      'error': error.toString(),
      'timestamp': DateTime.now().toIso8601String()
    };
    
    print('错误日志: $errorLog');
  }
  
  static void _setupLogging() {
    print('PrimitiveService日志系统已初始化');
  }
  
  static void _setupPerformanceMonitoring() {
    // 可以集成更复杂的性能监控系统
    print('性能监控已启用');
  }
}

/// 使用示例界面
class PrimitiveDemoScreen extends StatefulWidget {
  @override
  _PrimitiveDemoScreenState createState() => _PrimitiveDemoScreenState();
}

class _PrimitiveDemoScreenState extends State<PrimitiveDemoScreen> {
  Map<String, dynamic> _results = {};
  Map<String, bool> _loadingStates = {};
  Map<String, TextEditingController> _controllers = {};
  
  @override
  void initState() {
    super.initState();
    _initializeService();
    _initializeControllers();
  }
  
  Future<void> _initializeService() async {
    await PrimitiveService.initialize();
  }
  
  void _initializeControllers() {
    _controllers['int'] = TextEditingController(text: '42');
    _controllers['bool'] = TextEditingController(text: 'true');
    _controllers['string'] = TextEditingController(text: 'Hello HarmonyOS');
    _controllers['double'] = TextEditingController(text: '3.14159');
    _controllers['list'] = TextEditingController(text: '1,2,3,4,5');
    _controllers['map'] = TextEditingController(text: 'name:John,age:30,city:Beijing');
  }
  
  Future<void> _testInt() async {
    _setLoading('int', true);
    
    try {
      final input = int.tryParse(_controllers['int']!.text) ?? 42;
      final result = await PrimitiveService.testInt(input);
      
      setState(() {
        _results['int'] = '输入: $input, 输出: $result';
      });
    } catch (e) {
      setState(() {
        _results['int'] = '错误: $e';
      });
    } finally {
      _setLoading('int', false);
    }
  }
  
  Future<void> _testBool() async {
    _setLoading('bool', true);
    
    try {
      final input = _controllers['bool']!.text.toLowerCase() == 'true';
      final result = await PrimitiveService.testBool(input);
      
      setState(() {
        _results['bool'] = '输入: $input, 输出: $result';
      });
    } catch (e) {
      setState(() {
        _results['bool'] = '错误: $e';
      });
    } finally {
      _setLoading('bool', false);
    }
  }
  
  Future<void> _testString() async {
    _setLoading('string', true);
    
    try {
      final input = _controllers['string']!.text;
      final result = await PrimitiveService.testString(input);
      
      setState(() {
        _results['string'] = '输入长度: ${input.length}, 输出: ${result.substring(0, min(50, result.length))}...';
      });
    } catch (e) {
      setState(() {
        _results['string'] = '错误: $e';
      });
    } finally {
      _setLoading('string', false);
    }
  }
  
  Future<void> _testDouble() async {
    _setLoading('double', true);
    
    try {
      final input = double.tryParse(_controllers['double']!.text) ?? 3.14159;
      final result = await PrimitiveService.testDouble(input);
      
      setState(() {
        _results['double'] = '输入: $input, 输出: $result';
      });
    } catch (e) {
      setState(() {
        _results['double'] = '错误: $e';
      });
    } finally {
      _setLoading('double', false);
    }
  }
  
  Future<void> _testList() async {
    _setLoading('list', true);
    
    try {
      final text = _controllers['list']!.text;
      final items = text.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
      
      final result = await PrimitiveService.testList(items);
      
      setState(() {
        _results['list'] = '输入长度: ${items.length}, 输出长度: ${result.length}';
      });
    } catch (e) {
      setState(() {
        _results['list'] = '错误: $e';
      });
    } finally {
      _setLoading('list', false);
    }
  }
  
  Future<void> _testMap() async {
    _setLoading('map', true);
    
    try {
      final text = _controllers['map']!.text;
      final entries = text.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty);
      
      final map = <String, dynamic>{};
      for (final entry in entries) {
        final parts = entry.split(':');
        if (parts.length == 2) {
          map[parts[0].trim()] = parts[1].trim();
        }
      }
      
      final result = await PrimitiveService.testMap(map);
      
      setState(() {
        _results['map'] = '输入键数: ${map.length}, 输出键数: ${result.length}';
      });
    } catch (e) {
      setState(() {
        _results['map'] = '错误: $e';
      });
    } finally {
      _setLoading('map', false);
    }
  }
  
  void _setLoading(String key, bool isLoading) {
    setState(() {
      _loadingStates[key] = isLoading;
    });
  }
  
  bool _isLoading(String key) => _loadingStates[key] ?? false;
  
  Widget _buildTestCard({
    required String title,
    required String description,
    required String controllerKey,
    required String resultKey,
    required VoidCallback onTest,
  }) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            SizedBox(height: 8),
            Text(description),
            SizedBox(height: 12),
            TextField(
              controller: _controllers[controllerKey],
              decoration: InputDecoration(
                labelText: '输入值',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 12),
            ElevatedButton(
              onPressed: _isLoading(resultKey) ? null : onTest,
              child: _isLoading(resultKey)
                  ? CircularProgressIndicator()
                  : Text('测试'),
            ),
            SizedBox(height: 12),
            if (_results.containsKey(resultKey))
              Container(
                padding: EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(_results[resultKey]!),
              ),
          ],
        ),
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('基本数据类型测试')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            _buildTestCard(
              title: '整型测试',
              description: '测试整型数据的跨平台传递',
              controllerKey: 'int',
              resultKey: 'int',
              onTest: _testInt,
            ),
            SizedBox(height: 16),
            _buildTestCard(
              title: '布尔值测试',
              description: '测试布尔值的跨平台传递',
              controllerKey: 'bool',
              resultKey: 'bool',
              onTest: _testBool,
            ),
            SizedBox(height: 16),
            _buildTestCard(
              title: '字符串测试',
              description: '测试字符串的跨平台传递',
              controllerKey: 'string',
              resultKey: 'string',
              onTest: _testString,
            ),
            SizedBox(height: 16),
            _buildTestCard(
              title: '浮点数测试',
              description: '测试双精度浮点数的跨平台传递',
              controllerKey: 'double',
              resultKey: 'double',
              onTest: _testDouble,
            ),
            SizedBox(height: 16),
            _buildTestCard(
              title: '列表测试',
              description: '测试动态列表的跨平台传递',
              controllerKey: 'list',
              resultKey: 'list',
              onTest: _testList,
            ),
            SizedBox(height: 16),
            _buildTestCard(
              title: 'Map测试',
              description: '测试动态Map的跨平台传递',
              controllerKey: 'map',
              resultKey: 'map',
              onTest: _testMap,
            ),
          ],
        ),
      ),
    );
  }
}

五、性能优化与最佳实践

5.1 基本数据类型的性能特征

5.2 最佳实践建议

六、在鸿蒙生态中的特殊考虑

6.1 鸿蒙平台的类型系统适配

typescript 复制代码
// 鸿蒙平台类型适配器
export class HarmonyTypeAdapter {
  
  /**
   * Dart到鸿蒙类型转换
   */
  static dartToHarmony(dartValue: any): any {
    if (dartValue === null || dartValue === undefined) {
      return null;
    }
    
    const type = typeof dartValue;
    
    switch (type) {
      case 'number':
        // 区分整数和浮点数
        if (Number.isInteger(dartValue)) {
          // 鸿蒙中统一使用number,但可以标记类型
          return { type: 'int', value: dartValue };
        } else {
          return { type: 'double', value: dartValue };
        }
        
      case 'boolean':
        return dartValue;
        
      case 'string':
        // 鸿蒙字符串处理
        return this._processString(dartValue);
        
      case 'object':
        if (Array.isArray(dartValue)) {
          return this._processArray(dartValue);
        } else if (dartValue instanceof Int32Array) {
          return this._processInt32Array(dartValue);
        } else {
          return this._processObject(dartValue);
        }
        
      default:
        return dartValue;
    }
  }
  
  /**
   * 处理字符串(考虑鸿蒙的特殊编码需求)
   */
  private static _processString(str: string): string {
    // 鸿蒙可能需要特殊的字符串处理
    // 例如:emoji、特殊字符等
    return str;
  }
  
  /**
   * 处理数组
   */
  private static _processArray(arr: any[]): any[] {
    return arr.map(item => this.dartToHarmony(item));
  }
  
  /**
   * 处理Int32Array
   */
  private static _processInt32Array(arr: Int32Array): any {
    // 鸿蒙中可以使用TypedArray或普通数组
    return {
      type: 'Int32Array',
      data: Array.from(arr),
      length: arr.length
    };
  }
  
  /**
   * 处理对象
   */
  private static _processObject(obj: Record<string, any>): Record<string, any> {
    const result: Record<string, any> = {};
    
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        result[key] = this.dartToHarmony(obj[key]);
      }
    }
    
    return result;
  }
}

6.2 鸿蒙分布式场景的优化

typescript 复制代码
// 鸿蒙分布式基本数据类型优化
export class HarmonyDistributedPrimitive {
  
  /**
   * 优化基本数据类型用于分布式传输
   */
  static optimizeForDistribution(data: any): OptimizedData {
    const type = this._getDataType(data);
    
    switch (type) {
      case 'int':
      case 'double':
      case 'bool':
        // 基本类型直接传输
        return {
          type,
          value: data,
          size: this._getSize(data, type)
        };
        
      case 'string':
        // 字符串压缩优化
        return this._optimizeString(data);
        
      case 'array':
        // 数组分块优化
        return this._optimizeArray(data);
        
      case 'Int32Array':
        // 二进制优化
        return this._optimizeInt32Array(data);
        
      default:
        return {
          type: 'object',
          value: data,
          size: JSON.stringify(data).length
        };
    }
  }
  
  private static _optimizeString(str: string): OptimizedData {
    // 长字符串压缩
    if (str.length > 1000) {
      // 使用鸿蒙提供的压缩算法
      const compressed = this._compressString(str);
      return {
        type: 'compressed_string',
        value: compressed,
        size: compressed.length,
        originalSize: str.length
      };
    }
    
    return {
      type: 'string',
      value: str,
      size: str.length
    };
  }
  
  private static _optimizeArray(arr: any[]): OptimizedData {
    // 大数组分块
    if (arr.length > 1000) {
      const chunkSize = 500;
      const chunks: any[][] = [];
      
      for (let i = 0; i < arr.length; i += chunkSize) {
        chunks.push(arr.slice(i, i + chunkSize));
      }
      
      return {
        type: 'chunked_array',
        value: chunks,
        size: arr.length,
        chunkCount: chunks.length
      };
    }
    
    return {
      type: 'array',
      value: arr,
      size: arr.length
    };
  }
}

七、总结与展望

primitive.dart文件虽然内容相对基础,但它展示了Pigeon对Dart基本数据类型的全面支持。这些基本类型是所有复杂数据结构的基础,也是跨平台通信中最常用、最关键的部分:

  1. 全面性支持:覆盖了Dart的所有基本数据类型
  2. 性能优化:特别关注了Int32List等高效类型
  3. 类型安全:支持可空类型和泛型集合
  4. 平台适配:考虑了不同平台的类型系统差异

在鸿蒙生态中,基本数据类型的正确处理尤为重要:

  • 鸿蒙的分布式架构需要高效的数据序列化
  • 鸿蒙的多设备协同要求数据类型的一致性
  • 鸿蒙的性能优化需要对基本类型有深入理解

随着Flutter与鸿蒙的深度融合,Pigeon对基本数据类型的支持将成为构建高性能、高可靠性跨平台应用的关键技术。它不仅提供了技术实现,更体现了一种注重细节、追求性能的工程哲学。

欢迎大家加入开源鸿蒙跨平台开发者社区

相关推荐
星海浮沉2 小时前
一文了解 Flutter 动画
flutter·动画
小蜜蜂嗡嗡2 小时前
flutter PageView:竖直方向滑动,并且在屏幕中提前显示出下一页的四分之一
flutter
云川之下2 小时前
【网络】华为AR201路由器
网络·华为·智能路由器
翻斗花园岭第一爆破手2 小时前
flutter学习1
学习·flutter
kirk_wang2 小时前
鸿蒙与Flutter移动开发
flutter·移动开发·跨平台·arkts·鸿蒙
IT充电站3 小时前
鸿蒙应用开发之通过Swiper实现京东m站功能入口效果
harmonyos
IT充电站3 小时前
鸿蒙应用开发之通过Scroll、nestedScroll实现京东秒杀嵌套滚动效果
harmonyos
C雨后彩虹3 小时前
幼儿园分班
java·数据结构·算法·华为·面试
IT充电站3 小时前
鸿蒙应用开发之通过ListItemGroup、nestedScroll实现商城活动可折叠分组滚动效果
harmonyos