validate method

List<String> validate()

Checks that the voice number was propagated to the elements.

Returns one human-readable message per inconsistency, in element order: element at index i has voice=X but belongs to Voice Y. An empty list means the voice is internally consistent.

Propagation must happen when the note is built (Note.voice is final); this method exists so callers can detect a mismatch instead of silently rendering notes in the wrong voice.

Implementation

List<String> validate() {
  final problems = <String>[];
  for (var i = 0; i < elements.length; i++) {
    final element = elements[i];
    int? elementVoice;
    if (element is Note) {
      elementVoice = element.voice;
    } else if (element is Chord) {
      elementVoice = element.voice;
    } else {
      continue; // Rests and other elements do not carry a voice number.
    }
    if (elementVoice != number) {
      problems.add(
        'element at index $i has voice=${elementVoice ?? 'null'} '
        'but belongs to Voice $number',
      );
    }
  }
  return problems;
}