You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中ArrayBuffer与DataView的替代方案及JS转Dart代码求助

Dart 代码转换及类型替代方案

核心类型对应关系

Dart 中没有 ArrayBuffer 和 DataView,对应的替代类型都在 dart:typed_data 库中:

  • ByteBuffer 对应 JS 的 ArrayBuffer
  • ByteData 对应 JS 的 DataView(提供对 ByteBuffer 的读写操作)
  • Uint8List 对应 JS 的 Uint8Array

转换后的 Dart 代码

import 'dart:typed_data';

void main() {
  final password = "1234";
  final value = [0x00, 0x01, 0x00, 0x00, 0x00, 0x00];

  // 创建2字节的ByteData(对应JS的ArrayBuffer+DataView)
  final byteData = ByteData(2);
  // 字符串转整数,对应JS中隐式类型转换
  final passwordInt = int.parse(password);
  // 以小端序写入Uint16值
  byteData.setUint16(0, passwordInt, Endian.little);

  // 将ByteData转为Uint8List(对应JS的Uint8Array(arrPassword))
  final uint8ViewPassword = byteData.buffer.asUint8List();

  // 合并两个数组
  final valueUint8 = Uint8List.fromList(value);
  final mergedArray = Uint8List(valueUint8.length + uint8ViewPassword.length);
  mergedArray.setAll(0, valueUint8);
  mergedArray.setAll(valueUint8.length, uint8ViewPassword);

  // 可打印结果验证
  print(mergedArray);
}

关键细节说明

  • 必须导入 dart:typed_data 才能使用上述类型
  • Dart 不会隐式将字符串转为数字,需用 int.parse() 显式转换
  • 小端序通过 Endian.little 枚举指定,比 JS 的布尔参数更具可读性
  • 合并数组使用 setAll() 方法,逻辑与 JS 的 set() 完全一致

内容的提问来源于stack exchange,提问作者Siddy Hacks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 07:40:31