encode method

Uint8List encode()

Encode this NDEFRecord to raw byte data.

Implementation

Uint8List encode() {
  if (type == null) {
    throw ArgumentError.notNull(
        "Type is null, please set type before encode");
  }

  if (payload == null) {
    throw ArgumentError.notNull(
        "Payload is null, please set parameters or set payload directly before encode");
  }

  var encoded = <int>[];

  // check and canonicalize
  if (id == null) {
    flags.IL = false;
  } else {
    flags.IL = true;
  }

  if (payload!.length < 256) {
    flags.SR = true;
  } else {
    flags.SR = false;
  }

  // flags
  var encodedFlags = flags.encode();
  encoded.add(encodedFlags);

  // type length
  if (type!.length >= 256) {
    throw RangeError.range(type!.length, 0, 256);
  }

  encoded += [type!.length];

  // use getter for implicit encoding
  var encodedPayload = payload;

  // payload length
  if (encodedPayload!.length < 256) {
    encoded += [encodedPayload.length];
  } else {
    encoded += [
      encodedPayload.length & 0xff,
      (encodedPayload.length >> 8) & 0xff,
      (encodedPayload.length >> 16) & 0xff,
      (encodedPayload.length >> 24) & 0xff,
    ];
  }

  // ID length
  if (id != null) {
    if (id!.length >= 256) {
      throw RangeError.range(id!.length, 0, 256);
    }
    encoded += [id!.length];
  }

  // type
  encoded += type!;

  // ID
  if (id != null) {
    encoded += id!;
  }

  // payload
  encoded += encodedPayload;

  return Uint8List.fromList(encoded);
}