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

Dart中将double值转换为List<int>字节列表适配flutter_blue write方法咨询

你可以直接使用Dart标准库自带的dart:typed_data包完成转换,无需引入第三方依赖,具体实现如下:

1. 实现转换方法

import 'dart:typed_data';

/// 双精度浮点数(64位,占8字节)转字节列表
/// [endian] 为字节序,默认小端序,可根据蓝牙设备要求修改为Endian.big
List<int> doubleToBytes(double value, {Endian endian = Endian.little}) {
  final byteData = ByteData(8);
  byteData.setFloat64(0, value, endian);
  return byteData.buffer.asUint8List();
}

2. 使用示例

double value = 10.52;
List<int> convertedValue = doubleToBytes(value);
await bluetoothCharacteristic.write(convertedValue);

注意事项

  • 必须和对接的蓝牙设备约定好字节序(大端/小端),两端字节序不一致会导致数值解析错误
  • 如果设备仅支持32位单精度浮点数,可使用如下转换方法:
/// 单精度浮点数(32位,占4字节)转字节列表
List<int> floatToBytes(double value, {Endian endian = Endian.little}) {
  final byteData = ByteData(4);
  byteData.setFloat32(0, value, endian);
  return byteData.buffer.asUint8List();
}
  • 转换得到的Uint8List本身实现了List<int>接口,可直接传入write方法使用,无需额外类型转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:18:01