getLineBoundary method Null safety

TextRange getLineBoundary(
  1. TextPosition position
)

Returns the TextRange of the line at the given TextPosition.

The newline (if any) is returned as part of the range.

Not valid until after layout.

This can potentially be expensive, since it needs to compute the line metrics, so use it sparingly.

Implementation

TextRange getLineBoundary(TextPosition position) {
  final List<int> boundary = _getLineBoundary(position.offset);
  final TextRange line = TextRange(start: boundary[0], end: boundary[1]);

  final List<int> nextBoundary = _getLineBoundary(position.offset + 1);
  final TextRange nextLine = TextRange(start: nextBoundary[0], end: nextBoundary[1]);
  // If there is no next line, because we're at the end of the field, return
  // line.
  if (!nextLine.isValid) {
    return line;
  }

  // _getLineBoundary only considers the offset and assumes that the
  // TextAffinity is upstream. In the case that TextPosition is just after a
  // word wrap (downstream), we need to return the line for the next offset.
  if (position.affinity == TextAffinity.downstream && line != nextLine
      && position.offset == line.end && line.end == nextLine.start) {
    final List<int> nextBoundary = _getLineBoundary(position.offset + 1);
    return TextRange(start: nextBoundary[0], end: nextBoundary[1]);
  }
  return line;
}