encode method

Uint8List encode({
  1. int? maxChunkPayloadLength,
})

Encodes this message into its NDEF binary wire format.

The first physical record's MB bit and the last physical record's ME bit are set automatically. If maxChunkPayloadLength is given, any record whose payload is longer than it is split into a chunked sequence of physical records (CF = 1 on all but the last chunk, and TNF = UNCHANGED on all but the first); otherwise every record is encoded as a single, unchunked physical record.

Throws FormatException if records is empty, if any record's type or identifier is longer than 255 bytes, or if a record that would be chunked has an empty type and a TNF other than UNKNOWN. Throws ArgumentError if maxChunkPayloadLength is given and is less than 1.

Implementation

Uint8List encode({int? maxChunkPayloadLength}) {
  if (records.isEmpty) {
    throw FormatException('Cannot encode a message with no records.');
  }
  if (maxChunkPayloadLength != null && maxChunkPayloadLength < 1) {
    throw ArgumentError.value(
      maxChunkPayloadLength,
      'maxChunkPayloadLength',
      'Must be at least 1 when given.',
    );
  }

  final builder = BytesBuilder();
  var isFirstPhysicalRecord = true;

  for (var i = 0; i < records.length; i++) {
    final record = records[i];
    final isLastRecord = i == records.length - 1;
    final segments = record._splitPayload(maxChunkPayloadLength);

    for (var j = 0; j < segments.length; j++) {
      final isLastSegment = j == segments.length - 1;
      record._encodeSegment(
        builder,
        payload: segments[j],
        continuation: j > 0,
        chunkFlag: !isLastSegment,
        messageBegin: isFirstPhysicalRecord,
        messageEnd: isLastRecord && isLastSegment,
      );
      isFirstPhysicalRecord = false;
    }
  }

  return builder.toBytes();
}