performLayout method

  1. @override
void performLayout()

Do the actual work of computing this render object's layout.

This method must set size to the actual size of this render object within the given constraints. The constraints are accessible via the constraints getter.

Subclasses that have children should call layout on each child here and position them appropriately.

Example implementation:

@override
void performLayout() {
  // For a leaf node, just pick a size within constraints
  size = constraints.constrain(Size(desiredWidth, desiredHeight));

  // For a node with children:
  // 1. Layout children with appropriate constraints
  // 2. Position children (set their parentData.offset)
  // 3. Set this node's size based on children
}

Implementation

@override
void performLayout() {
  if (child == null) {
    size = constraints.constrain(Size.zero);
    return;
  }

  // Give the child unbounded space so it can report its intrinsic size.
  child!.layout(const BoxConstraints(), parentUsesSize: true);
  final childSize = child!.size;

  final double childAspectRatio = childSize.width / childSize.height;
  final double availableWidth = constraints.maxWidth;
  final double availableHeight = constraints.maxHeight;
  final double availableAspectRatio = availableWidth / availableHeight;

  // Determine the target size based on [fit].
  final Size fittedSize = _computeFittedSize(
    fit: fit,
    childSize: childSize,
    childAspectRatio: childAspectRatio,
    availableWidth: availableWidth,
    availableHeight: availableHeight,
    availableAspectRatio: availableAspectRatio,
  );

  size = constraints.constrain(fittedSize);

  // Compute the alignment offset so the child is positioned correctly within
  // the fitted bounds.
  final double xOffset = alignment.x * (size.width - childSize.width) / 2;
  final double yOffset = alignment.y * (size.height - childSize.height) / 2;

  // Ensure the child's parent data is initialised before writing the offset.
  if (child!.parentData == null) {
    child!.parentData = BoxParentData();
  }
  (child!.parentData as BoxParentData).offset = Offset(xOffset, yOffset);
}