NdefRecord constructor

NdefRecord({
  1. required NdefTypeNameFormat typeNameFormat,
  2. required Uint8List type,
  3. required Uint8List identifier,
  4. required Uint8List payload,
})

Constructs a record, rejecting shapes the NDEF specification forbids.

Prefer TextRecord.create, UriRecord.create and friends, which also get the payload encoding right.

Implementation

factory NdefRecord({
  required NdefTypeNameFormat typeNameFormat,
  required Uint8List type,
  required Uint8List identifier,
  required Uint8List payload,
}) {
  switch (typeNameFormat) {
    case NdefTypeNameFormat.empty:
      if (type.isNotEmpty || identifier.isNotEmpty || payload.isNotEmpty) {
        throw ArgumentError('an empty record carries no type, identifier or payload');
      }
    case NdefTypeNameFormat.unknown:
      if (type.isNotEmpty) throw ArgumentError('an unknown-format record carries no type');
    case NdefTypeNameFormat.unchanged:
      throw ArgumentError('unchanged is only valid on a chunk continuation, not a whole record');
    case NdefTypeNameFormat.wellKnown:
    case NdefTypeNameFormat.media:
    case NdefTypeNameFormat.absoluteUri:
    case NdefTypeNameFormat.external:
      break;
  }

  // TYPE_LENGTH and ID_LENGTH are one byte each on the wire. Truncating instead of
  // refusing would produce a record that encodes without complaint and that nothing --
  // not this package's own parser, not the platform's -- can read back.
  if (type.length > 255) {
    throw ArgumentError.value(type.length, 'type', 'does not fit the one-byte TYPE_LENGTH field');
  }
  if (identifier.length > 255) {
    throw ArgumentError.value(identifier.length, 'identifier', 'does not fit the one-byte ID_LENGTH field');
  }

  return NdefRecord._(typeNameFormat: typeNameFormat, type: type, identifier: identifier, payload: payload);
}