create<T extends Union> static method

  1. @Since('3.4')
T create<T extends Union>(
  1. [TypedData typedData,
  2. int offset]
)

Creates a union view of bytes in typedData.

The created instance of the union subclass will then be backed by the bytes at TypedData.offsetInBytes plus offset times TypedData.elementSizeInBytes. That is, the getters and setters of the external instance variables declared by the subclass, will read an write their values from the bytes of the TypedData.buffer of typedData, starting at TypedData.offsetInBytes plus offset times TypedData.elementSizeInBytes. The TypedData.lengthInBytes of typedData must be sufficient to contain the sizeOf of the union subclass. It doesn't matter whether the typedData is, for example, a Uint8List, a Float64List, or any other TypedData, it's only treated as a view into a ByteBuffer, through its TypedData.buffer, TypedData.offsetInBytes and TypedData.lengthInBytes.

If typedData is omitted, a fresh ByteBuffer, with precisely enough bytes for the sizeOf of the created union, is allocated on the Dart heap, and used as memory to store the union fields.

If offset is provided, the indexing into typedData is offset by offset times TypedData.elementSizeInBytes.

Example:

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);
  }
}

To create a union object from a Pointer, use UnionPointer.ref.

Implementation

@Since('3.4')
external static T create<T extends Union>([TypedData typedData, int offset]);