snapToGrid method

Offset snapToGrid(
  1. Offset position
)

Snaps a position to the grid if grid snapping is enabled.

This is a convenience method that accesses the GridSnapDelegate through the snap delegate chain. Returns the position unchanged if:

  • No snap delegate is set
  • The snap delegate doesn't contain a GridSnapDelegate
  • Grid snapping is disabled

Use this for snapping positions when adding nodes, pasting, or other programmatic position updates.

Example:

final snappedPos = controller.snapToGrid(position);
node.setPosition(snappedPos);

Implementation

Offset snapToGrid(Offset position) {
  // First try the attached delegate
  final delegate = _snapDelegate;
  if (delegate is SnapPlugin) {
    // Only snap if plugin is enabled
    if (!delegate.enabled) return position;
    return delegate.gridSnapDelegate?.snapPoint(position) ?? position;
  }
  if (delegate is GridSnapDelegate) {
    return delegate.snapPoint(position);
  }

  // Fall back to plugin registry (for unit tests without initController)
  final snapExt = _config.pluginRegistry.get<SnapPlugin>();
  if (snapExt != null) {
    // Only snap if plugin is enabled
    if (!snapExt.enabled) return position;
    return snapExt.gridSnapDelegate?.snapPoint(position) ?? position;
  }

  return position;
}