table.dart 46.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Hixie's avatar
Hixie committed
2 3 4 5 6 7
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:collection';
import 'dart:math' as math;

8 9
import 'package:flutter/foundation.dart';

Hixie's avatar
Hixie committed
10 11
import 'box.dart';
import 'object.dart';
12
import 'table_border.dart';
Hixie's avatar
Hixie committed
13 14 15

/// Parent data used by [RenderTable] for its children.
class TableCellParentData extends BoxParentData {
16
  /// Where this cell should be placed vertically.
17 18
  ///
  /// When using [TableCellVerticalAlignment.baseline], the text baseline must be set as well.
19
  TableCellVerticalAlignment? verticalAlignment;
Hixie's avatar
Hixie committed
20

Hixie's avatar
Hixie committed
21
  /// The column that the child was in the last time it was laid out.
22
  int? x;
Hixie's avatar
Hixie committed
23 24

  /// The row that the child was in the last time it was laid out.
25
  int? y;
Hixie's avatar
Hixie committed
26

Hixie's avatar
Hixie committed
27
  @override
28
  String toString() => '${super.toString()}; ${verticalAlignment == null ? "default vertical alignment" : "$verticalAlignment"}';
Hixie's avatar
Hixie committed
29 30 31
}

/// Base class to describe how wide a column in a [RenderTable] should be.
32 33 34 35 36 37 38 39
///
/// To size a column to a specific number of pixels, use a [FixedColumnWidth].
/// This is the cheapest way to size a column.
///
/// Other algorithms that are relatively cheap include [FlexColumnWidth], which
/// distributes the space equally among the flexible columns,
/// [FractionColumnWidth], which sizes a column based on the size of the
/// table's container.
40
@immutable
Hixie's avatar
Hixie committed
41
abstract class TableColumnWidth {
42 43
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
Hixie's avatar
Hixie committed
44 45
  const TableColumnWidth();

46 47 48 49 50 51 52 53
  /// The smallest width that the column can have.
  ///
  /// The `cells` argument is an iterable that provides all the cells
  /// in the table for this column. Walking the cells is by definition
  /// O(N), so algorithms that do that should be considered expensive.
  ///
  /// The `containerWidth` argument is the `maxWidth` of the incoming
  /// constraints for the table, and might be infinite.
Hixie's avatar
Hixie committed
54 55
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth);

56 57 58 59 60 61 62 63 64 65 66 67
  /// The ideal width that the column should have. This must be equal
  /// to or greater than the [minIntrinsicWidth]. The column might be
  /// bigger than this width, e.g. if the column is flexible or if the
  /// table's width ends up being forced to be bigger than the sum of
  /// all the maxIntrinsicWidth values.
  ///
  /// The `cells` argument is an iterable that provides all the cells
  /// in the table for this column. Walking the cells is by definition
  /// O(N), so algorithms that do that should be considered expensive.
  ///
  /// The `containerWidth` argument is the `maxWidth` of the incoming
  /// constraints for the table, and might be infinite.
Hixie's avatar
Hixie committed
68 69
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth);

70 71 72 73 74 75 76 77
  /// The flex factor to apply to the cell if there is any room left
  /// over when laying out the table. The remaining space is
  /// distributed to any columns with flex in proportion to their flex
  /// value (higher values get more space).
  ///
  /// The `cells` argument is an iterable that provides all the cells
  /// in the table for this column. Walking the cells is by definition
  /// O(N), so algorithms that do that should be considered expensive.
78
  double? flex(Iterable<RenderBox> cells) => null;
Hixie's avatar
Hixie committed
79 80

  @override
81
  String toString() => objectRuntimeType(this, 'TableColumnWidth');
Hixie's avatar
Hixie committed
82 83 84 85 86 87
}

/// Sizes the column according to the intrinsic dimensions of all the
/// cells in that column.
///
/// This is a very expensive way to size a column.
88 89 90 91
///
/// A flex value can be provided. If specified (and non-null), the
/// column will participate in the distribution of remaining space
/// once all the non-flexible columns have been sized.
92
class IntrinsicColumnWidth extends TableColumnWidth {
93 94 95
  /// Creates a column width based on intrinsic sizing.
  ///
  /// This sizing algorithm is very expensive.
96 97 98 99 100
  ///
  /// The `flex` argument specifies the flex factor to apply to the column if
  /// there is any room left over when laying out the table. If `flex` is
  /// null (the default), the table will not distribute any extra space to the
  /// column.
101
  const IntrinsicColumnWidth({ double? flex }) : _flex = flex;
Hixie's avatar
Hixie committed
102 103 104 105

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    double result = 0.0;
106
    for (final RenderBox cell in cells)
107
      result = math.max(result, cell.getMinIntrinsicWidth(double.infinity));
Hixie's avatar
Hixie committed
108 109 110 111 112 113
    return result;
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    double result = 0.0;
114
    for (final RenderBox cell in cells)
115
      result = math.max(result, cell.getMaxIntrinsicWidth(double.infinity));
Hixie's avatar
Hixie committed
116 117
    return result;
  }
118

119
  final double? _flex;
120 121

  @override
122
  double? flex(Iterable<RenderBox> cells) => _flex;
123 124

  @override
125
  String toString() => '${objectRuntimeType(this, 'IntrinsicColumnWidth')}(flex: ${_flex?.toStringAsFixed(1)})';
Hixie's avatar
Hixie committed
126 127 128 129 130 131
}

/// Sizes the column to a specific number of pixels.
///
/// This is the cheapest way to size a column.
class FixedColumnWidth extends TableColumnWidth {
132 133 134
  /// Creates a column width based on a fixed number of logical pixels.
  ///
  /// The [value] argument must not be null.
135
  const FixedColumnWidth(this.value) : assert(value != null);
136 137

  /// The width the column should occupy in logical pixels.
Hixie's avatar
Hixie committed
138 139 140 141 142 143 144 145 146 147 148 149 150
  final double value;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return value;
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return value;
  }

  @override
151
  String toString() => '${objectRuntimeType(this, 'FixedColumnWidth')}(${debugFormatDouble(value)})';
Hixie's avatar
Hixie committed
152 153 154 155 156 157
}

/// Sizes the column to a fraction of the table's constraints' maxWidth.
///
/// This is a cheap way to size a column.
class FractionColumnWidth extends TableColumnWidth {
158 159 160 161
  /// Creates a column width based on a fraction of the table's constraints'
  /// maxWidth.
  ///
  /// The [value] argument must not be null.
162
  const FractionColumnWidth(this.value) : assert(value != null);
163 164 165

  /// The fraction of the table's constraints' maxWidth that this column should
  /// occupy.
Hixie's avatar
Hixie committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
  final double value;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    if (!containerWidth.isFinite)
      return 0.0;
    return value * containerWidth;
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    if (!containerWidth.isFinite)
      return 0.0;
    return value * containerWidth;
  }

  @override
183
  String toString() => '${objectRuntimeType(this, 'FractionColumnWidth')}($value)';
Hixie's avatar
Hixie committed
184 185 186 187 188
}

/// Sizes the column by taking a part of the remaining space once all
/// the other columns have been laid out.
///
189
/// For example, if two columns have a [FlexColumnWidth], then half the
Hixie's avatar
Hixie committed
190 191 192 193
/// space will go to one and half the space will go to the other.
///
/// This is a cheap way to size a column.
class FlexColumnWidth extends TableColumnWidth {
194 195 196 197
  /// Creates a column width based on a fraction of the remaining space once all
  /// the other columns have been laid out.
  ///
  /// The [value] argument must not be null.
198
  const FlexColumnWidth([this.value = 1.0]) : assert(value != null);
199

200
  /// The fraction of the remaining space once all the other columns have
201
  /// been laid out that this column should occupy.
Hixie's avatar
Hixie committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  final double value;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return 0.0;
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return 0.0;
  }

  @override
  double flex(Iterable<RenderBox> cells) {
    return value;
  }

  @override
220
  String toString() => '${objectRuntimeType(this, 'FlexColumnWidth')}(${debugFormatDouble(value)})';
Hixie's avatar
Hixie committed
221 222 223 224 225 226 227 228 229 230 231 232 233
}

/// Sizes the column such that it is the size that is the maximum of
/// two column width specifications.
///
/// For example, to have a column be 10% of the container width or
/// 100px, whichever is bigger, you could use:
///
///     const MaxColumnWidth(const FixedColumnWidth(100.0), FractionColumnWidth(0.1))
///
/// Both specifications are evaluated, so if either specification is
/// expensive, so is this.
class MaxColumnWidth extends TableColumnWidth {
234
  /// Creates a column width that is the maximum of two other column widths.
Hixie's avatar
Hixie committed
235
  const MaxColumnWidth(this.a, this.b);
236 237

  /// A lower bound for the width of this column.
Hixie's avatar
Hixie committed
238
  final TableColumnWidth a;
239 240

  /// Another lower bound for the width of this column.
Hixie's avatar
Hixie committed
241 242 243 244 245 246
  final TableColumnWidth b;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return math.max(
      a.minIntrinsicWidth(cells, containerWidth),
247
      b.minIntrinsicWidth(cells, containerWidth),
Hixie's avatar
Hixie committed
248 249 250 251 252 253 254
    );
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return math.max(
      a.maxIntrinsicWidth(cells, containerWidth),
255
      b.maxIntrinsicWidth(cells, containerWidth),
Hixie's avatar
Hixie committed
256 257 258 259
    );
  }

  @override
260 261
  double? flex(Iterable<RenderBox> cells) {
    final double? aFlex = a.flex(cells);
Hixie's avatar
Hixie committed
262 263
    if (aFlex == null)
      return b.flex(cells);
264
    final double? bFlex = b.flex(cells);
265 266 267
    if (bFlex == null)
      return null;
    return math.max(aFlex, bFlex);
Hixie's avatar
Hixie committed
268 269 270
  }

  @override
271
  String toString() => '${objectRuntimeType(this, 'MaxColumnWidth')}($a, $b)';
Hixie's avatar
Hixie committed
272 273 274 275 276 277 278 279 280 281 282 283 284
}

/// Sizes the column such that it is the size that is the minimum of
/// two column width specifications.
///
/// For example, to have a column be 10% of the container width but
/// never bigger than 100px, you could use:
///
///     const MinColumnWidth(const FixedColumnWidth(100.0), FractionColumnWidth(0.1))
///
/// Both specifications are evaluated, so if either specification is
/// expensive, so is this.
class MinColumnWidth extends TableColumnWidth {
285 286 287 288
  /// Creates a column width that is the minimum of two other column widths.
  const MinColumnWidth(this.a, this.b);

  /// An upper bound for the width of this column.
Hixie's avatar
Hixie committed
289
  final TableColumnWidth a;
290 291

  /// Another upper bound for the width of this column.
Hixie's avatar
Hixie committed
292 293 294 295 296 297
  final TableColumnWidth b;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return math.min(
      a.minIntrinsicWidth(cells, containerWidth),
298
      b.minIntrinsicWidth(cells, containerWidth),
Hixie's avatar
Hixie committed
299 300 301 302 303 304 305
    );
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return math.min(
      a.maxIntrinsicWidth(cells, containerWidth),
306
      b.maxIntrinsicWidth(cells, containerWidth),
Hixie's avatar
Hixie committed
307 308 309 310
    );
  }

  @override
311 312
  double? flex(Iterable<RenderBox> cells) {
    final double? aFlex = a.flex(cells);
Hixie's avatar
Hixie committed
313 314
    if (aFlex == null)
      return b.flex(cells);
315
    final double? bFlex = b.flex(cells);
316 317 318
    if (bFlex == null)
      return null;
    return math.min(aFlex, bFlex);
Hixie's avatar
Hixie committed
319 320 321
  }

  @override
322
  String toString() => '${objectRuntimeType(this, 'MinColumnWidth')}($a, $b)';
Hixie's avatar
Hixie committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
}

/// Vertical alignment options for cells in [RenderTable] objects.
///
/// This is specified using [TableCellParentData] objects on the
/// [RenderObject.parentData] of the children of the [RenderTable].
enum TableCellVerticalAlignment {
  /// Cells with this alignment are placed with their top at the top of the row.
  top,

  /// Cells with this alignment are vertically centered in the row.
  middle,

  /// Cells with this alignment are placed with their bottom at the bottom of the row.
  bottom,

  /// Cells with this alignment are aligned such that they all share the same
  /// baseline. Cells with no baseline are top-aligned instead. The baseline
Ian Hickson's avatar
Ian Hickson committed
341 342
  /// used is specified by [RenderTable.textBaseline]. It is not valid to use
  /// the baseline value if [RenderTable.textBaseline] is not specified.
343
  ///
344
  /// This vertical alignment is relatively expensive because it causes the table
345
  /// to compute the baseline for each cell in the row.
Hixie's avatar
Hixie committed
346 347 348 349 350 351 352 353 354
  baseline,

  /// Cells with this alignment are sized to be as tall as the row, then made to fit the row.
  /// If all the cells have this alignment, then the row will have zero height.
  fill
}

/// A table where the columns and rows are sized to fit the contents of the cells.
class RenderTable extends RenderBox {
355 356 357 358 359 360 361 362 363 364
  /// Creates a table render object.
  ///
  ///  * `columns` must either be null or non-negative. If `columns` is null,
  ///    the number of columns will be inferred from length of the first sublist
  ///    of `children`.
  ///  * `rows` must either be null or non-negative. If `rows` is null, the
  ///    number of rows will be inferred from the `children`. If `rows` is not
  ///    null, then `children` must be null.
  ///  * `children` must either be null or contain lists of all the same length.
  ///    if `children` is not null, then `rows` must be null.
365
  ///  * [columnWidths] may be null, in which case it defaults to an empty map.
366
  ///  * [defaultColumnWidth] must not be null.
367
  ///  * [configuration] must not be null (but has a default value).
Hixie's avatar
Hixie committed
368
  RenderTable({
369 370 371
    int? columns,
    int? rows,
    Map<int, TableColumnWidth>? columnWidths,
372
    TableColumnWidth defaultColumnWidth = const FlexColumnWidth(),
373 374 375
    required TextDirection textDirection,
    TableBorder? border,
    List<Decoration?>? rowDecorations,
376 377
    ImageConfiguration configuration = ImageConfiguration.empty,
    TableCellVerticalAlignment defaultVerticalAlignment = TableCellVerticalAlignment.top,
378 379
    TextBaseline? textBaseline,
    List<List<RenderBox>>? children,
380 381 382 383
  }) : assert(columns == null || columns >= 0),
       assert(rows == null || rows >= 0),
       assert(rows == null || children == null),
       assert(defaultColumnWidth != null),
384 385
       assert(textDirection != null),
       assert(configuration != null),
386 387 388 389 390 391 392 393 394
       _textDirection = textDirection,
       _columns = columns ?? (children != null && children.isNotEmpty ? children.first.length : 0),
       _rows = rows ?? 0,
       _columnWidths = columnWidths ?? HashMap<int, TableColumnWidth>(),
       _defaultColumnWidth = defaultColumnWidth,
       _border = border,
       _textBaseline = textBaseline,
       _defaultVerticalAlignment = defaultVerticalAlignment,
       _configuration = configuration {
395
    _children = <RenderBox?>[]..length = _columns * _rows;
396
    this.rowDecorations = rowDecorations; // must use setter to initialize box painters array
397
    children?.forEach(addRow);
Hixie's avatar
Hixie committed
398 399 400 401
  }

  // Children are stored in row-major order.
  // _children.length must be rows * columns
402
  List<RenderBox?> _children = const <RenderBox?>[];
Hixie's avatar
Hixie committed
403

404 405 406 407 408 409
  /// The number of vertical alignment lines in this table.
  ///
  /// Changing the number of columns will remove any children that no longer fit
  /// in the table.
  ///
  /// Changing the number of columns is an expensive operation because the table
410
  /// needs to rearrange its internal representation.
Hixie's avatar
Hixie committed
411 412
  int get columns => _columns;
  int _columns;
413
  set columns(int value) {
Hixie's avatar
Hixie committed
414 415 416 417
    assert(value != null);
    assert(value >= 0);
    if (value == columns)
      return;
418
    final int oldColumns = columns;
419
    final List<RenderBox?> oldChildren = _children;
Hixie's avatar
Hixie committed
420
    _columns = value;
421
    _children = List<RenderBox?>.filled(columns * rows, null);
422
    final int columnsToCopy = math.min(columns, oldColumns);
Hixie's avatar
Hixie committed
423 424 425 426
    for (int y = 0; y < rows; y += 1) {
      for (int x = 0; x < columnsToCopy; x += 1)
        _children[x + y * columns] = oldChildren[x + y * oldColumns];
    }
Hixie's avatar
Hixie committed
427 428 429
    if (oldColumns > columns) {
      for (int y = 0; y < rows; y += 1) {
        for (int x = columns; x < oldColumns; x += 1) {
430
          final int xy = x + y * oldColumns;
Hixie's avatar
Hixie committed
431
          if (oldChildren[xy] != null)
432
            dropChild(oldChildren[xy]!);
Hixie's avatar
Hixie committed
433 434 435
        }
      }
    }
Hixie's avatar
Hixie committed
436 437 438
    markNeedsLayout();
  }

439 440 441 442
  /// The number of horizontal alignment lines in this table.
  ///
  /// Changing the number of rows will remove any children that no longer fit
  /// in the table.
Hixie's avatar
Hixie committed
443 444
  int get rows => _rows;
  int _rows;
445
  set rows(int value) {
Hixie's avatar
Hixie committed
446 447 448 449
    assert(value != null);
    assert(value >= 0);
    if (value == rows)
      return;
Hixie's avatar
Hixie committed
450 451 452
    if (_rows > value) {
      for (int xy = columns * value; xy < _children.length; xy += 1) {
        if (_children[xy] != null)
453
          dropChild(_children[xy]!);
Hixie's avatar
Hixie committed
454 455
      }
    }
Hixie's avatar
Hixie committed
456 457 458 459 460
    _rows = value;
    _children.length = columns * rows;
    markNeedsLayout();
  }

461 462 463 464 465 466 467 468 469
  /// How the horizontal extents of the columns of this table should be determined.
  ///
  /// If the [Map] has a null entry for a given column, the table uses the
  /// [defaultColumnWidth] instead.
  ///
  /// The layout performance of the table depends critically on which column
  /// sizing algorithms are used here. In particular, [IntrinsicColumnWidth] is
  /// quite expensive because it needs to measure each cell in the column to
  /// determine the intrinsic size of the column.
470 471 472 473 474
  ///
  /// This property can never return null. If it is set to null, and the existing
  /// map is not empty, then the value is replaced by an empty map. (If it is set
  /// to null while the current value is an empty map, the value is not changed.)
  Map<int, TableColumnWidth>? get columnWidths => Map<int, TableColumnWidth>.unmodifiable(_columnWidths);
475
  Map<int, TableColumnWidth> _columnWidths;
476
  set columnWidths(Map<int, TableColumnWidth>? value) {
Hixie's avatar
Hixie committed
477 478
    if (_columnWidths == value)
      return;
479 480 481
    if (_columnWidths.isEmpty && value == null)
      return;
    _columnWidths = value ?? HashMap<int, TableColumnWidth>();
Hixie's avatar
Hixie committed
482 483 484
    markNeedsLayout();
  }

485
  /// Determines how the width of column with the given index is determined.
Hixie's avatar
Hixie committed
486 487 488 489 490 491 492
  void setColumnWidth(int column, TableColumnWidth value) {
    if (_columnWidths[column] == value)
      return;
    _columnWidths[column] = value;
    markNeedsLayout();
  }

493 494 495 496
  /// How to determine with widths of columns that don't have an explicit sizing algorithm.
  ///
  /// Specifically, the [defaultColumnWidth] is used for column `i` if
  /// `columnWidths[i]` is null.
Hixie's avatar
Hixie committed
497 498
  TableColumnWidth get defaultColumnWidth => _defaultColumnWidth;
  TableColumnWidth _defaultColumnWidth;
499
  set defaultColumnWidth(TableColumnWidth value) {
Hixie's avatar
Hixie committed
500 501 502 503 504 505 506
    assert(value != null);
    if (defaultColumnWidth == value)
      return;
    _defaultColumnWidth = value;
    markNeedsLayout();
  }

507 508 509 510 511 512 513 514 515 516 517
  /// The direction in which the columns are ordered.
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
    if (_textDirection == value)
      return;
    _textDirection = value;
    markNeedsLayout();
  }

518
  /// The style to use when painting the boundary and interior divisions of the table.
519 520 521
  TableBorder? get border => _border;
  TableBorder? _border;
  set border(TableBorder? value) {
Hixie's avatar
Hixie committed
522 523 524 525 526
    if (border == value)
      return;
    _border = value;
    markNeedsPaint();
  }
527

528 529 530 531 532
  /// The decorations to use for each row of the table.
  ///
  /// Row decorations fill the horizontal and vertical extent of each row in
  /// the table, unlike decorations for individual cells, which might not fill
  /// either.
533
  List<Decoration> get rowDecorations => List<Decoration>.unmodifiable(_rowDecorations ?? const <Decoration>[]);
534 535
  // _rowDecorations and _rowDecorationPainters need to be in sync. They have to
  // either both be null or have same length.
536 537 538
  List<Decoration?>? _rowDecorations;
  List<BoxPainter?>? _rowDecorationPainters;
  set rowDecorations(List<Decoration?>? value) {
539 540 541
    if (_rowDecorations == value)
      return;
    _rowDecorations = value;
542
    if (_rowDecorationPainters != null) {
543
      for (final BoxPainter? painter in _rowDecorationPainters!)
544
        painter?.dispose();
545
    }
546
    _rowDecorationPainters = _rowDecorations != null ? List<BoxPainter?>.filled(_rowDecorations!.length, null) : null;
547 548
  }

549 550 551 552 553
  /// The settings to pass to the [rowDecorations] when painting, so that they
  /// can resolve images appropriately. See [ImageProvider.resolve] and
  /// [BoxPainter.paint].
  ImageConfiguration get configuration => _configuration;
  ImageConfiguration _configuration;
554
  set configuration(ImageConfiguration value) {
555 556 557 558 559
    assert(value != null);
    if (value == _configuration)
      return;
    _configuration = value;
    markNeedsPaint();
560
  }
Hixie's avatar
Hixie committed
561

562
  /// How cells that do not explicitly specify a vertical alignment are aligned vertically.
Hixie's avatar
Hixie committed
563 564
  TableCellVerticalAlignment get defaultVerticalAlignment => _defaultVerticalAlignment;
  TableCellVerticalAlignment _defaultVerticalAlignment;
565
  set defaultVerticalAlignment(TableCellVerticalAlignment value) {
566
    assert(value != null);
Hixie's avatar
Hixie committed
567 568 569 570 571 572
    if (_defaultVerticalAlignment == value)
      return;
    _defaultVerticalAlignment = value;
    markNeedsLayout();
  }

573
  /// The text baseline to use when aligning rows using [TableCellVerticalAlignment.baseline].
574 575 576
  TextBaseline? get textBaseline => _textBaseline;
  TextBaseline? _textBaseline;
  set textBaseline(TextBaseline? value) {
Hixie's avatar
Hixie committed
577 578 579 580 581 582 583 584 585
    if (_textBaseline == value)
      return;
    _textBaseline = value;
    markNeedsLayout();
  }

  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! TableCellParentData)
586
      child.parentData = TableCellParentData();
Hixie's avatar
Hixie committed
587 588
  }

589 590 591 592 593 594 595 596
  /// Replaces the children of this table with the given cells.
  ///
  /// The cells are divided into the specified number of columns before
  /// replacing the existing children.
  ///
  /// If the new cells contain any existing children of the table, those
  /// children are simply moved to their new location in the table rather than
  /// removed from the table and re-added.
597
  void setFlatChildren(int columns, List<RenderBox?> cells) {
Hixie's avatar
Hixie committed
598 599 600
    if (cells == _children && columns == _columns)
      return;
    assert(columns >= 0);
Hixie's avatar
Hixie committed
601
    // consider the case of a newly empty table
602 603
    if (columns == 0 || cells.isEmpty) {
      assert(cells == null || cells.isEmpty);
Hixie's avatar
Hixie committed
604
      _columns = columns;
605
      if (_children.isEmpty) {
Hixie's avatar
Hixie committed
606
        assert(_rows == 0);
Hixie's avatar
Hixie committed
607
        return;
Hixie's avatar
Hixie committed
608
      }
609
      for (final RenderBox? oldChild in _children) {
Hixie's avatar
Hixie committed
610 611 612
        if (oldChild != null)
          dropChild(oldChild);
      }
Hixie's avatar
Hixie committed
613 614 615 616 617 618 619
      _rows = 0;
      _children.clear();
      markNeedsLayout();
      return;
    }
    assert(cells != null);
    assert(cells.length % columns == 0);
620 621 622
    // fill a set with the cells that are moving (it's important not
    // to dropChild a child that's remaining with us, because that
    // would clear their parentData field)
623
    final Set<RenderBox> lostChildren = HashSet<RenderBox>();
Hixie's avatar
Hixie committed
624 625
    for (int y = 0; y < _rows; y += 1) {
      for (int x = 0; x < _columns; x += 1) {
626 627
        final int xyOld = x + y * _columns;
        final int xyNew = x + y * columns;
Hixie's avatar
Hixie committed
628
        if (_children[xyOld] != null && (x >= columns || xyNew >= cells.length || _children[xyOld] != cells[xyNew]))
629
          lostChildren.add(_children[xyOld]!);
Hixie's avatar
Hixie committed
630
      }
Hixie's avatar
Hixie committed
631
    }
632
    // adopt cells that are arriving, and cross cells that are just moving off our list of lostChildren
Hixie's avatar
Hixie committed
633 634 635
    int y = 0;
    while (y * columns < cells.length) {
      for (int x = 0; x < columns; x += 1) {
636 637
        final int xyNew = x + y * columns;
        final int xyOld = x + y * _columns;
638 639
        if (cells[xyNew] != null && (x >= _columns || y >= _rows || _children[xyOld] != cells[xyNew])) {
          if (!lostChildren.remove(cells[xyNew]))
640
            adoptChild(cells[xyNew]!);
641
        }
Hixie's avatar
Hixie committed
642 643 644
      }
      y += 1;
    }
645
    // drop all the lost children
646
    lostChildren.forEach(dropChild);
Hixie's avatar
Hixie committed
647 648 649
    // update our internal values
    _columns = columns;
    _rows = cells.length ~/ columns;
650
    _children = List<RenderBox?>.of(cells);
Hixie's avatar
Hixie committed
651
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
652 653 654
    markNeedsLayout();
  }

655
  /// Replaces the children of this table with the given cells.
656
  void setChildren(List<List<RenderBox>>? cells) {
Hixie's avatar
Hixie committed
657
    // TODO(ianh): Make this smarter, like setFlatChildren
Hixie's avatar
Hixie committed
658
    if (cells == null) {
659
      setFlatChildren(0, const <RenderBox?>[]);
Hixie's avatar
Hixie committed
660 661
      return;
    }
662
    for (final RenderBox? oldChild in _children) {
Hixie's avatar
Hixie committed
663 664 665
      if (oldChild != null)
        dropChild(oldChild);
    }
Hixie's avatar
Hixie committed
666
    _children.clear();
667
    _columns = cells.isNotEmpty ? cells.first.length : 0;
Hixie's avatar
Hixie committed
668
    _rows = 0;
669
    cells.forEach(addRow);
Hixie's avatar
Hixie committed
670
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
671 672
  }

673 674 675
  /// Adds a row to the end of the table.
  ///
  /// The newly added children must not already have parents.
676
  void addRow(List<RenderBox?> cells) {
Hixie's avatar
Hixie committed
677
    assert(cells.length == columns);
Hixie's avatar
Hixie committed
678
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
679 680
    _rows += 1;
    _children.addAll(cells);
681
    for (final RenderBox? cell in cells) {
Hixie's avatar
Hixie committed
682 683 684 685 686 687
      if (cell != null)
        adoptChild(cell);
    }
    markNeedsLayout();
  }

688 689 690 691 692
  /// Replaces the child at the given position with the given child.
  ///
  /// If the given child is already located at the given position, this function
  /// does not modify the table. Otherwise, the given child must not already
  /// have a parent.
693
  void setChild(int x, int y, RenderBox? value) {
Hixie's avatar
Hixie committed
694 695 696
    assert(x != null);
    assert(y != null);
    assert(x >= 0 && x < columns && y >= 0 && y < rows);
Hixie's avatar
Hixie committed
697
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
698
    final int xy = x + y * columns;
699
    final RenderBox? oldChild = _children[xy];
Hixie's avatar
Hixie committed
700 701
    if (oldChild == value)
      return;
Hixie's avatar
Hixie committed
702 703 704 705 706 707 708 709 710 711
    if (oldChild != null)
      dropChild(oldChild);
    _children[xy] = value;
    if (value != null)
      adoptChild(value);
  }

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
712
    for (final RenderBox? child in _children)
Hixie's avatar
Hixie committed
713 714 715 716 717
      child?.attach(owner);
  }

  @override
  void detach() {
718
    super.detach();
719
    if (_rowDecorationPainters != null) {
720
      for (final BoxPainter? painter in _rowDecorationPainters!)
721
        painter?.dispose();
722
      _rowDecorationPainters = List<BoxPainter?>.filled(_rowDecorations!.length, null);
723
    }
724
    for (final RenderBox? child in _children)
Hixie's avatar
Hixie committed
725 726 727 728 729
      child?.detach();
  }

  @override
  void visitChildren(RenderObjectVisitor visitor) {
Hixie's avatar
Hixie committed
730
    assert(_children.length == rows * columns);
731
    for (final RenderBox? child in _children) {
Hixie's avatar
Hixie committed
732 733 734 735 736 737
      if (child != null)
        visitor(child);
    }
  }

  @override
738
  double computeMinIntrinsicWidth(double height) {
Hixie's avatar
Hixie committed
739
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
740 741
    double totalMinWidth = 0.0;
    for (int x = 0; x < columns; x += 1) {
742 743
      final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth;
      final Iterable<RenderBox> columnCells = column(x);
744
      totalMinWidth += columnWidth.minIntrinsicWidth(columnCells, double.infinity);
Hixie's avatar
Hixie committed
745
    }
746
    return totalMinWidth;
Hixie's avatar
Hixie committed
747 748 749
  }

  @override
750
  double computeMaxIntrinsicWidth(double height) {
Hixie's avatar
Hixie committed
751
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
752 753
    double totalMaxWidth = 0.0;
    for (int x = 0; x < columns; x += 1) {
754 755
      final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth;
      final Iterable<RenderBox> columnCells = column(x);
756
      totalMaxWidth += columnWidth.maxIntrinsicWidth(columnCells, double.infinity);
Hixie's avatar
Hixie committed
757
    }
758
    return totalMaxWidth;
Hixie's avatar
Hixie committed
759 760 761
  }

  @override
762
  double computeMinIntrinsicHeight(double width) {
Hixie's avatar
Hixie committed
763 764
    // winner of the 2016 world's most expensive intrinsic dimension function award
    // honorable mention, most likely to improve if taught about memoization award
Hixie's avatar
Hixie committed
765
    assert(_children.length == rows * columns);
766
    final List<double> widths = _computeColumnWidths(BoxConstraints.tightForFinite(width: width));
Hixie's avatar
Hixie committed
767 768 769 770 771
    double rowTop = 0.0;
    for (int y = 0; y < rows; y += 1) {
      double rowHeight = 0.0;
      for (int x = 0; x < columns; x += 1) {
        final int xy = x + y * columns;
772
        final RenderBox? child = _children[xy];
Hixie's avatar
Hixie committed
773
        if (child != null)
774
          rowHeight = math.max(rowHeight, child.getMaxIntrinsicHeight(widths[x]));
Hixie's avatar
Hixie committed
775 776 777
      }
      rowTop += rowHeight;
    }
778
    return rowTop;
Hixie's avatar
Hixie committed
779 780 781
  }

  @override
782 783
  double computeMaxIntrinsicHeight(double width) {
    return computeMinIntrinsicHeight(width);
Hixie's avatar
Hixie committed
784 785
  }

786
  double? _baselineDistance;
Hixie's avatar
Hixie committed
787
  @override
788
  double? computeDistanceToActualBaseline(TextBaseline baseline) {
Hixie's avatar
Hixie committed
789
    // returns the baseline of the first cell that has a baseline in the first row
790
    assert(!debugNeedsLayout);
Hixie's avatar
Hixie committed
791 792 793
    return _baselineDistance;
  }

794 795 796 797
  /// Returns the list of [RenderBox] objects that are in the given
  /// column, in row order, starting from the first row.
  ///
  /// This is a lazily-evaluated iterable.
798 799
  // The following uses sync* because it is public API documented to return a
  // lazy iterable.
Hixie's avatar
Hixie committed
800 801 802
  Iterable<RenderBox> column(int x) sync* {
    for (int y = 0; y < rows; y += 1) {
      final int xy = x + y * columns;
803
      final RenderBox? child = _children[xy];
Hixie's avatar
Hixie committed
804 805 806 807 808
      if (child != null)
        yield child;
    }
  }

809 810 811 812
  /// Returns the list of [RenderBox] objects that are on the given
  /// row, in column order, starting with the first column.
  ///
  /// This is a lazily-evaluated iterable.
813 814
  // The following uses sync* because it is public API documented to return a
  // lazy iterable.
Hixie's avatar
Hixie committed
815 816 817 818
  Iterable<RenderBox> row(int y) sync* {
    final int start = y * columns;
    final int end = (y + 1) * columns;
    for (int xy = start; xy < end; xy += 1) {
819
      final RenderBox? child = _children[xy];
Hixie's avatar
Hixie committed
820 821 822 823 824
      if (child != null)
        yield child;
    }
  }

825
  List<double> _computeColumnWidths(BoxConstraints constraints) {
826
    assert(constraints != null);
Hixie's avatar
Hixie committed
827
    assert(_children.length == rows * columns);
828 829 830 831 832 833 834 835 836 837 838
    // We apply the constraints to the column widths in the order of
    // least important to most important:
    // 1. apply the ideal widths (maxIntrinsicWidth)
    // 2. grow the flex columns so that the table has the maxWidth (if
    //    finite) or the minWidth (if not)
    // 3. if there were no flex columns, then grow the table to the
    //    minWidth.
    // 4. apply the maximum width of the table, shrinking columns as
    //    necessary, applying minimum column widths as we go

    // 1. apply ideal widths, and collect information we'll need later
839 840 841
    final List<double> widths = List<double>.filled(columns, 0.0);
    final List<double> minWidths = List<double>.filled(columns, 0.0);
    final List<double?> flexes = List<double?>.filled(columns, null);
842 843
    double tableWidth = 0.0; // running tally of the sum of widths[x] for all x
    double unflexedTableWidth = 0.0; // sum of the maxIntrinsicWidths of any column that has null flex
Hixie's avatar
Hixie committed
844 845
    double totalFlex = 0.0;
    for (int x = 0; x < columns; x += 1) {
846 847
      final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth;
      final Iterable<RenderBox> columnCells = column(x);
848 849 850 851 852 853 854 855 856 857 858 859 860
      // apply ideal width (maxIntrinsicWidth)
      final double maxIntrinsicWidth = columnWidth.maxIntrinsicWidth(columnCells, constraints.maxWidth);
      assert(maxIntrinsicWidth.isFinite);
      assert(maxIntrinsicWidth >= 0.0);
      widths[x] = maxIntrinsicWidth;
      tableWidth += maxIntrinsicWidth;
      // collect min width information while we're at it
      final double minIntrinsicWidth = columnWidth.minIntrinsicWidth(columnCells, constraints.maxWidth);
      assert(minIntrinsicWidth.isFinite);
      assert(minIntrinsicWidth >= 0.0);
      minWidths[x] = minIntrinsicWidth;
      assert(maxIntrinsicWidth >= minIntrinsicWidth);
      // collect flex information while we're at it
861
      final double? flex = columnWidth.flex(columnCells);
Hixie's avatar
Hixie committed
862
      if (flex != null) {
863 864
        assert(flex.isFinite);
        assert(flex > 0.0);
Hixie's avatar
Hixie committed
865 866
        flexes[x] = flex;
        totalFlex += flex;
867
      } else {
868
        unflexedTableWidth = unflexedTableWidth + maxIntrinsicWidth;
Hixie's avatar
Hixie committed
869 870
      }
    }
871 872 873 874 875 876 877 878
    final double maxWidthConstraint = constraints.maxWidth;
    final double minWidthConstraint = constraints.minWidth;

    // 2. grow the flex columns so that the table has the maxWidth (if
    //    finite) or the minWidth (if not)
    if (totalFlex > 0.0) {
      // this can only grow the table, but it _will_ grow the table at
      // least as big as the target width.
879
      final double targetWidth;
880
      if (maxWidthConstraint.isFinite) {
881
        targetWidth = maxWidthConstraint;
882 883 884 885 886 887 888
      } else {
        targetWidth = minWidthConstraint;
      }
      if (tableWidth < targetWidth) {
        final double remainingWidth = targetWidth - unflexedTableWidth;
        assert(remainingWidth.isFinite);
        assert(remainingWidth >= 0.0);
Hixie's avatar
Hixie committed
889 890
        for (int x = 0; x < columns; x += 1) {
          if (flexes[x] != null) {
891
            final double flexedWidth = remainingWidth * flexes[x]! / totalFlex;
892 893 894 895 896 897 898
            assert(flexedWidth.isFinite);
            assert(flexedWidth >= 0.0);
            if (widths[x] < flexedWidth) {
              final double delta = flexedWidth - widths[x];
              tableWidth += delta;
              widths[x] = flexedWidth;
            }
Hixie's avatar
Hixie committed
899 900
          }
        }
901
        assert(tableWidth + precisionErrorTolerance >= targetWidth);
902
      }
903
    } // step 2 and 3 are mutually exclusive
904 905 906

    // 3. if there were no flex columns, then grow the table to the
    //    minWidth.
907
    else if (tableWidth < minWidthConstraint) {
908 909
      final double delta = (minWidthConstraint - tableWidth) / columns;
      for (int x = 0; x < columns; x += 1)
910
        widths[x] = widths[x] + delta;
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
      tableWidth = minWidthConstraint;
    }

    // beyond this point, unflexedTableWidth is no longer valid

    // 4. apply the maximum width of the table, shrinking columns as
    //    necessary, applying minimum column widths as we go
    if (tableWidth > maxWidthConstraint) {
      double deficit = tableWidth - maxWidthConstraint;
      // Some columns may have low flex but have all the free space.
      // (Consider a case with a 1px wide column of flex 1000.0 and
      // a 1000px wide column of flex 1.0; the sizes coming from the
      // maxIntrinsicWidths. If the maximum table width is 2px, then
      // just applying the flexes to the deficit would result in a
      // table with one column at -998px and one column at 990px,
      // which is wildly unhelpful.)
      // Similarly, some columns may be flexible, but not actually
      // be shrinkable due to a large minimum width. (Consider a
      // case with two columns, one is flex and one isn't, both have
      // 1000px maxIntrinsicWidths, but the flex one has 1000px
      // minIntrinsicWidth also. The whole deficit will have to come
      // from the non-flex column.)
      // So what we do is we repeatedly iterate through the flexible
      // columns shrinking them proportionally until we have no
      // available columns, then do the same to the non-flexible ones.
      int availableColumns = columns;
937
      while (deficit > precisionErrorTolerance && totalFlex > precisionErrorTolerance) {
938 939 940
        double newTotalFlex = 0.0;
        for (int x = 0; x < columns; x += 1) {
          if (flexes[x] != null) {
941
            final double newWidth = widths[x] - deficit * flexes[x]! / totalFlex;
942 943 944 945 946 947 948 949 950 951
            assert(newWidth.isFinite);
            if (newWidth <= minWidths[x]) {
              // shrank to minimum
              deficit -= widths[x] - minWidths[x];
              widths[x] = minWidths[x];
              flexes[x] = null;
              availableColumns -= 1;
            } else {
              deficit -= widths[x] - newWidth;
              widths[x] = newWidth;
952
              newTotalFlex += flexes[x]!;
953
            }
954
            assert(widths[x] >= 0.0);
955 956 957 958
          }
        }
        totalFlex = newTotalFlex;
      }
959
      while (deficit > precisionErrorTolerance && availableColumns > 0) {
960 961 962 963 964
        // Now we have to take out the remaining space from the
        // columns that aren't minimum sized.
        // To make this fair, we repeatedly remove equal amounts from
        // each column, clamped to the minimum width, until we run out
        // of columns that aren't at their minWidth.
965 966 967 968 969 970 971 972 973 974 975 976
        final double delta = deficit / availableColumns;
        assert(delta != 0);
        int newAvailableColumns = 0;
        for (int x = 0; x < columns; x += 1) {
          final double availableDelta = widths[x] - minWidths[x];
          if (availableDelta > 0.0) {
            if (availableDelta <= delta) {
              // shrank to minimum
              deficit -= widths[x] - minWidths[x];
              widths[x] = minWidths[x];
            } else {
              deficit -= delta;
977
              widths[x] = widths[x] - delta;
978
              newAvailableColumns += 1;
979 980
            }
          }
981 982
        }
        availableColumns = newAvailableColumns;
Hixie's avatar
Hixie committed
983 984 985 986 987 988
      }
    }
    return widths;
  }

  // cache the table geometry for painting purposes
989
  final List<double> _rowTops = <double>[];
990
  Iterable<double>? _columnLefts;
Hixie's avatar
Hixie committed
991

992 993 994 995 996 997 998 999 1000 1001
  /// Returns the position and dimensions of the box that the given
  /// row covers, in this render object's coordinate space (so the
  /// left coordinate is always 0.0).
  ///
  /// The row being queried must exist.
  ///
  /// This is only valid after layout.
  Rect getRowBox(int row) {
    assert(row >= 0);
    assert(row < rows);
1002
    assert(!debugNeedsLayout);
1003
    return Rect.fromLTRB(0.0, _rowTops[row], size.width, _rowTops[row + 1]);
1004 1005
  }

1006 1007 1008
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    if (rows * columns == 0) {
1009
      return constraints.constrain(Size.zero);
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
    }
    final List<double> widths = _computeColumnWidths(constraints);
    final double tableWidth = widths.fold(0.0, (double a, double b) => a + b);
    double rowTop = 0.0;
    for (int y = 0; y < rows; y += 1) {
      double rowHeight = 0.0;
      for (int x = 0; x < columns; x += 1) {
        final int xy = x + y * columns;
        final RenderBox? child = _children[xy];
        if (child != null) {
          final TableCellParentData childParentData = child.parentData! as TableCellParentData;
          assert(childParentData != null);
          switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) {
            case TableCellVerticalAlignment.baseline:
              assert(debugCannotComputeDryLayout(
1025
                reason: 'TableCellVerticalAlignment.baseline requires a full layout for baseline metrics to be available.',
1026
              ));
1027
              return Size.zero;
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
            case TableCellVerticalAlignment.top:
            case TableCellVerticalAlignment.middle:
            case TableCellVerticalAlignment.bottom:
              final Size childSize = child.getDryLayout(BoxConstraints.tightFor(width: widths[x]));
              rowHeight = math.max(rowHeight, childSize.height);
              break;
            case TableCellVerticalAlignment.fill:
              break;
          }
        }
      }
      rowTop += rowHeight;
    }
    return constraints.constrain(Size(tableWidth, rowTop));
  }

Hixie's avatar
Hixie committed
1044 1045
  @override
  void performLayout() {
1046
    final BoxConstraints constraints = this.constraints;
1047 1048
    final int rows = this.rows;
    final int columns = this.columns;
Hixie's avatar
Hixie committed
1049
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
1050
    if (rows * columns == 0) {
Hixie's avatar
Hixie committed
1051 1052
      // TODO(ianh): if columns is zero, this should be zero width
      // TODO(ianh): if columns is not zero, this should be based on the column width specifications
1053
      size = constraints.constrain(Size.zero);
Hixie's avatar
Hixie committed
1054 1055
      return;
    }
1056
    final List<double> widths = _computeColumnWidths(constraints);
1057
    final List<double> positions = List<double>.filled(columns, 0.0);
1058
    final double tableWidth;
1059 1060 1061 1062 1063
    switch (textDirection) {
      case TextDirection.rtl:
        positions[columns - 1] = 0.0;
        for (int x = columns - 2; x >= 0; x -= 1)
          positions[x] = positions[x+1] + widths[x+1];
1064
        _columnLefts = positions.reversed;
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
        tableWidth = positions.first + widths.first;
        break;
      case TextDirection.ltr:
        positions[0] = 0.0;
        for (int x = 1; x < columns; x += 1)
          positions[x] = positions[x-1] + widths[x-1];
        _columnLefts = positions;
        tableWidth = positions.last + widths.last;
        break;
    }
    _rowTops.clear();
Hixie's avatar
Hixie committed
1076 1077 1078 1079 1080 1081 1082 1083 1084
    _baselineDistance = null;
    // then, lay out each row
    double rowTop = 0.0;
    for (int y = 0; y < rows; y += 1) {
      _rowTops.add(rowTop);
      double rowHeight = 0.0;
      bool haveBaseline = false;
      double beforeBaselineDistance = 0.0;
      double afterBaselineDistance = 0.0;
1085
      final List<double> baselines = List<double>.filled(columns, 0.0);
Hixie's avatar
Hixie committed
1086 1087
      for (int x = 0; x < columns; x += 1) {
        final int xy = x + y * columns;
1088
        final RenderBox? child = _children[xy];
Hixie's avatar
Hixie committed
1089
        if (child != null) {
1090
          final TableCellParentData childParentData = child.parentData! as TableCellParentData;
Hixie's avatar
Hixie committed
1091
          assert(childParentData != null);
Hixie's avatar
Hixie committed
1092 1093
          childParentData.x = x;
          childParentData.y = y;
Hixie's avatar
Hixie committed
1094 1095
          switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) {
            case TableCellVerticalAlignment.baseline:
1096
              assert(textBaseline != null, 'An explicit textBaseline is required when using baseline alignment.');
1097
              child.layout(BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true);
1098
              final double? childBaseline = child.getDistanceToBaseline(textBaseline!, onlyReal: true);
Hixie's avatar
Hixie committed
1099 1100 1101 1102 1103 1104 1105
              if (childBaseline != null) {
                beforeBaselineDistance = math.max(beforeBaselineDistance, childBaseline);
                afterBaselineDistance = math.max(afterBaselineDistance, child.size.height - childBaseline);
                baselines[x] = childBaseline;
                haveBaseline = true;
              } else {
                rowHeight = math.max(rowHeight, child.size.height);
1106
                childParentData.offset = Offset(positions[x], rowTop);
Hixie's avatar
Hixie committed
1107 1108 1109 1110 1111
              }
              break;
            case TableCellVerticalAlignment.top:
            case TableCellVerticalAlignment.middle:
            case TableCellVerticalAlignment.bottom:
1112
              child.layout(BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true);
Hixie's avatar
Hixie committed
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
              rowHeight = math.max(rowHeight, child.size.height);
              break;
            case TableCellVerticalAlignment.fill:
              break;
          }
        }
      }
      if (haveBaseline) {
        if (y == 0)
          _baselineDistance = beforeBaselineDistance;
        rowHeight = math.max(rowHeight, beforeBaselineDistance + afterBaselineDistance);
      }
      for (int x = 0; x < columns; x += 1) {
        final int xy = x + y * columns;
1127
        final RenderBox? child = _children[xy];
Hixie's avatar
Hixie committed
1128
        if (child != null) {
1129
          final TableCellParentData childParentData = child.parentData! as TableCellParentData;
Hixie's avatar
Hixie committed
1130 1131
          switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) {
            case TableCellVerticalAlignment.baseline:
1132
              childParentData.offset = Offset(positions[x], rowTop + beforeBaselineDistance - baselines[x]);
Hixie's avatar
Hixie committed
1133 1134
              break;
            case TableCellVerticalAlignment.top:
1135
              childParentData.offset = Offset(positions[x], rowTop);
Hixie's avatar
Hixie committed
1136 1137
              break;
            case TableCellVerticalAlignment.middle:
1138
              childParentData.offset = Offset(positions[x], rowTop + (rowHeight - child.size.height) / 2.0);
Hixie's avatar
Hixie committed
1139 1140
              break;
            case TableCellVerticalAlignment.bottom:
1141
              childParentData.offset = Offset(positions[x], rowTop + rowHeight - child.size.height);
Hixie's avatar
Hixie committed
1142 1143
              break;
            case TableCellVerticalAlignment.fill:
1144 1145
              child.layout(BoxConstraints.tightFor(width: widths[x], height: rowHeight));
              childParentData.offset = Offset(positions[x], rowTop);
Hixie's avatar
Hixie committed
1146 1147 1148 1149 1150 1151
              break;
          }
        }
      }
      rowTop += rowHeight;
    }
1152
    _rowTops.add(rowTop);
1153
    size = constraints.constrain(Size(tableWidth, rowTop));
1154
    assert(_rowTops.length == rows + 1);
Hixie's avatar
Hixie committed
1155 1156 1157
  }

  @override
1158
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
Hixie's avatar
Hixie committed
1159
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
1160
    for (int index = _children.length - 1; index >= 0; index -= 1) {
1161
      final RenderBox? child = _children[index];
Hixie's avatar
Hixie committed
1162
      if (child != null) {
1163
        final BoxParentData childParentData = child.parentData! as BoxParentData;
1164 1165 1166
        final bool isHit = result.addWithPaintOffset(
          offset: childParentData.offset,
          position: position,
1167
          hitTest: (BoxHitTestResult result, Offset transformed) {
1168
            assert(transformed == position - childParentData.offset);
1169
            return child.hitTest(result, position: transformed);
1170 1171 1172
          },
        );
        if (isHit)
Hixie's avatar
Hixie committed
1173 1174 1175 1176 1177 1178 1179 1180
          return true;
      }
    }
    return false;
  }

  @override
  void paint(PaintingContext context, Offset offset) {
Hixie's avatar
Hixie committed
1181
    assert(_children.length == rows * columns);
1182
    if (rows * columns == 0) {
1183
      if (border != null) {
1184
        final Rect borderRect = Rect.fromLTWH(offset.dx, offset.dy, size.width, 0.0);
1185
        border!.paint(context.canvas, borderRect, rows: const <double>[], columns: const <double>[]);
1186
      }
Hixie's avatar
Hixie committed
1187
      return;
1188
    }
1189 1190
    assert(_rowTops.length == rows + 1);
    if (_rowDecorations != null) {
1191
      assert(_rowDecorations!.length == _rowDecorationPainters!.length);
1192
      final Canvas canvas = context.canvas;
1193
      for (int y = 0; y < rows; y += 1) {
1194
        if (_rowDecorations!.length <= y)
1195
          break;
1196 1197 1198
        if (_rowDecorations![y] != null) {
          _rowDecorationPainters![y] ??= _rowDecorations![y]!.createBoxPainter(markNeedsPaint);
          _rowDecorationPainters![y]!.paint(
1199
            canvas,
1200
            Offset(offset.dx, offset.dy + _rowTops[y]),
1201
            configuration.copyWith(size: Size(size.width, _rowTops[y+1] - _rowTops[y])),
1202
          );
1203
        }
1204 1205
      }
    }
Hixie's avatar
Hixie committed
1206
    for (int index = 0; index < _children.length; index += 1) {
1207
      final RenderBox? child = _children[index];
Hixie's avatar
Hixie committed
1208
      if (child != null) {
1209
        final BoxParentData childParentData = child.parentData! as BoxParentData;
Hixie's avatar
Hixie committed
1210 1211 1212
        context.paintChild(child, childParentData.offset + offset);
      }
    }
1213
    assert(_rows == _rowTops.length - 1);
1214
    assert(_columns == _columnLefts!.length);
1215 1216 1217 1218
    if (border != null) {
      // The border rect might not fill the entire height of this render object
      // if the rows underflow. We always force the columns to fill the width of
      // the render object, which means the columns cannot underflow.
1219
      final Rect borderRect = Rect.fromLTWH(offset.dx, offset.dy, size.width, _rowTops.last);
1220
      final Iterable<double> rows = _rowTops.getRange(1, _rowTops.length - 1);
1221 1222
      final Iterable<double> columns = _columnLefts!.skip(1);
      border!.paint(context.canvas, borderRect, rows: rows, columns: columns);
1223
    }
Hixie's avatar
Hixie committed
1224 1225 1226
  }

  @override
1227 1228
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1229 1230 1231 1232
    properties.add(DiagnosticsProperty<TableBorder>('border', border, defaultValue: null));
    properties.add(DiagnosticsProperty<Map<int, TableColumnWidth>>('specified column widths', _columnWidths, level: _columnWidths.isEmpty ? DiagnosticLevel.hidden : DiagnosticLevel.info));
    properties.add(DiagnosticsProperty<TableColumnWidth>('default column width', defaultColumnWidth));
    properties.add(MessageProperty('table size', '$columns\u00D7$rows'));
1233
    properties.add(IterableProperty<String>('column offsets', _columnLefts?.map(debugFormatDouble), ifNull: 'unknown'));
1234
    properties.add(IterableProperty<String>('row offsets', _rowTops.map(debugFormatDouble), ifNull: 'unknown'));
Hixie's avatar
Hixie committed
1235 1236 1237
  }

  @override
1238 1239
  List<DiagnosticsNode> debugDescribeChildren() {
    if (_children.isEmpty) {
1240
      return <DiagnosticsNode>[DiagnosticsNode.message('table is empty')];
1241 1242 1243 1244 1245 1246
    }

    final List<DiagnosticsNode> children = <DiagnosticsNode>[];
    for (int y = 0; y < rows; y += 1) {
      for (int x = 0; x < columns; x += 1) {
        final int xy = x + y * columns;
1247
        final RenderBox? child = _children[xy];
1248 1249 1250 1251
        final String name = 'child ($x, $y)';
        if (child != null)
          children.add(child.toDiagnosticsNode(name: name));
        else
1252
          children.add(DiagnosticsProperty<Object>(name, null, ifNull: 'is null', showSeparator: false));
Hixie's avatar
Hixie committed
1253 1254
      }
    }
1255
    return children;
Hixie's avatar
Hixie committed
1256 1257
  }
}