create<T extends Union> 静态方法
- @Since('3.4')
在typedData中创建字节的联合视图。
然后创建的联合子类的实例将由TypedData.offsetInBytes加上offset乘以TypedData.elementSizeInBytes处的字节支持。也就是说,子类声明的外部实例变量的getters和setters将从TypedData.buffer的字节中读取和写入它们的值,起始位置为TypedData.offsetInBytes加上offset乘以TypedData.elementSizeInBytes。typedData的TypedData.lengthInBytes 必须足以包含联合子类的sizeOf。不管typedData是,例如,Uint8List,Float64List,还是任何其他TypedData,它仅被视为通过其TypedData.buffer,TypedData.offsetInBytes和TypedData.lengthInBytes的ByteBuffer视图。
如果省略了typedData,则在Dart堆上分配一个全新的ByteBuffer,其字节精确足够用于创建的联合的大小,并用作存储联合字段的内存。
如果提供了offset,则typedData的索引将偏移offset乘以TypedData.elementSizeInBytes。
示例
final class MyUnion extends Union {
@Int32()
external int a;
@Float()
external double b;
/// Creates Dart managed memory to hold a `MyUnion` and returns the
/// `MyUnion` view on it.
factory MyUnion.a(int a) {
return Union.create()..a = a;
}
/// Creates Dart managed memory to hold a `MyUnion` and returns the
/// `MyUnion` view on it.
factory MyUnion.b(double b) {
return Union.create()..b = b;
}
/// Creates a [MyUnion] view on [typedData].
factory MyUnion.fromTypedData(TypedData typedData) {
return Union.create(typedData);
}
}
要从Pointer创建联合对象,请使用UnionPointer.ref。
实现
@Since('3.4')
external static T create<T extends Union>([TypedData typedData, int offset]);