getSemantics method Null safety

SemanticsNode getSemantics (
  1. Finder finder
)

Attempts to find the SemanticsNode of first result from finder.

If the object identified by the finder doesn't own it's semantic node, this will return the semantics data of the first ancestor with semantics. The ancestor's semantic data will include the child's as well as other nodes that have been merged together.

If the SemanticsNode of the object identified by the finder is force-merged into an ancestor (e.g. via the MergeSemantics widget) the node into which it is merged is returned. That node will include all the semantics information of the nodes merged into it.

Will throw a StateError if the finder returns more than one element or if no semantics are found or are not enabled.

Implementation

SemanticsNode getSemantics(Finder finder) {
  if (binding.pipelineOwner.semanticsOwner == null)
    throw StateError('Semantics are not enabled.');
  final Iterable<Element> candidates = finder.evaluate();
  if (candidates.isEmpty) {
    throw StateError('Finder returned no matching elements.');
  }
  if (candidates.length > 1) {
    throw StateError('Finder returned more than one element.');
  }
  final Element element = candidates.single;
  RenderObject renderObject = element.findRenderObject();
  SemanticsNode result = renderObject.debugSemantics;
  while (renderObject != null && (result == null || result.isMergedIntoParent)) {
    renderObject = renderObject?.parent as RenderObject;
    result = renderObject?.debugSemantics;
  }
  if (result == null)
    throw StateError('No Semantics data found.');
  return result;
}