layout method Null safety

  1. @override
void layout(
  1. Context context,
  2. BoxConstraints constraints,
  3. {bool parentUsesSize = false}
)
override

First widget pass to calculate the children layout and bounding box

Implementation

@override
void layout(Context context, BoxConstraints constraints,
    {bool parentUsesSize = false}) {
  // Determine used flex factor, size inflexible items, calculate free space.
  final maxMainSize = constraints.maxWidth;
  final canFlex = maxMainSize < double.infinity;
  var allocatedSize = 0.0; // Sum of the sizes of the non-flexible children.
  var totalFlex = 0;
  final widths = List<double?>.filled(children.length, 0);

  // Calculate fixed width columns
  var index = 0;
  for (var child in children) {
    if (child.flex > 0) {
      assert(() {
        if (!canFlex) {
          throw Exception(
              'Partition children have non-zero flex but incoming width constraints are unbounded.');
        } else {
          return true;
        }
      }());
      totalFlex += child.flex;
    } else {
      allocatedSize += child.width!;
      widths[index] = child.width;
    }
    index++;
  }

  // Distribute free space to flexible children, and determine baseline.
  if (totalFlex > 0 && canFlex) {
    final freeSpace =
        math.max(0, (canFlex ? maxMainSize : 0.0) - allocatedSize);
    final spacePerFlex = freeSpace / totalFlex;

    index = 0;
    for (var child in children) {
      if (child.flex > 0) {
        final childExtent = spacePerFlex * child.flex;
        allocatedSize += childExtent;
        widths[index] = childExtent;
      }
      index++;
    }
  }

  // Layout the columns and compute the total height
  var totalHeight = 0.0;
  index = 0;
  for (var child in children) {
    if (widths[index]! > 0) {
      final innerConstraints = BoxConstraints(
          minWidth: widths[index]!,
          maxWidth: widths[index]!,
          maxHeight: constraints.maxHeight);

      child.layout(context, innerConstraints);
      assert(child.box != null);
      totalHeight = math.max(totalHeight, child.box!.height);
    }
    index++;
  }

  // Update Y positions
  index = 0;
  allocatedSize = 0.0;
  for (var child in children) {
    if (widths[index]! > 0) {
      final offsetY = totalHeight - child.box!.height;
      child.box = PdfRect.fromPoints(
          PdfPoint(allocatedSize, offsetY), child.box!.size);
      totalHeight = math.max(totalHeight, child.box!.height);
      allocatedSize += widths[index]!;
    }
    index++;
  }

  box = PdfRect(0, 0, allocatedSize, totalHeight);
}