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

Dart中如何统一声明所有内置类型化列表,解决TypedData无length报错?

报错原因

Dart 内置的TypedData抽象类仅定义了字节缓冲相关的通用属性(如elementSizeInBytes、buffer、offsetInBytes),并未声明length getter。你用到的所有数值类型化列表(Float64List/Int32List等)都同时实现了TypedData和List<对应数值类型>两个接口,仅用TypedData作为类型约束自然无法访问List接口的length属性。


最优解决方案(Dart 3.0+)

Dart 3.0 支持类型交集语法,可以直接声明变量同时符合两个接口的约束,完美满足你的需求:既保留TypedData的字节相关属性访问能力,又能直接调用List的length、索引操作等通用方法。
修改后的代码如下:

import 'dart:typed_data';

class BufferAttribute {
  /// 支持的类型化列表:
  /// - Float64List
  /// - Float32List
  /// - Int32List
  /// - Uint32List
  /// - Int16List
  /// - Uint16List
  /// - Uint8ClampedList
  /// - Uint8List
  /// - Int8List
  /// 可存储位置、颜色、法线、uv、索引等数据
  final TypedData & List<num> array;

  /// 每个元素的分量数,可选1/2/3/4
  final int itemSize;
  final bool normalized;

  /// 元素总数 = 数组长度 / 分量数
  late final int count;

  /// 默认值对应gl.STATIC_DRAW
  final int usage = 35044;

  BufferAttribute(this.array, this.itemSize, [this.normalized = false]) {
    count = array.length ~/ itemSize;
  }
}

这种写法自带编译期类型检查,不符合约束的变量(比如ByteData)会直接在编译阶段报错,不需要额外运行时校验。


兼容Dart 2.x的解决方案

如果你的项目还没有升级到Dart 3,可以根据你的使用场景二选一:

  1. 不需要访问TypedData字节属性
    直接将array的类型声明为List<num>即可,所有你用到的数值类型化列表都可以直接赋值给该类型变量,能正常访问length和索引操作。
  2. 需要保留TypedData属性访问能力
    保留TypedData类型声明,使用类型断言访问List属性,同时加运行时校验避免非法传参:
import 'dart:typed_data';

class BufferAttribute {
  final TypedData array;
  final int itemSize;
  final bool normalized;
  late final int count;
  final int usage = 35044;

  BufferAttribute(this.array, this.itemSize, [this.normalized = false]) {
    assert(array is List, '传入的TypedData必须为数值类型化列表');
    count = (array as List).length ~/ itemSize;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:36:02