table.dart 17 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
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:collection';

7
import 'package:flutter/foundation.dart';
Hixie's avatar
Hixie committed
8 9
import 'package:flutter/rendering.dart';

10
import 'basic.dart';
Hixie's avatar
Hixie committed
11 12
import 'debug.dart';
import 'framework.dart';
13
import 'image.dart';
Hixie's avatar
Hixie committed
14 15

export 'package:flutter/rendering.dart' show
16 17 18 19 20 21 22 23 24
  FixedColumnWidth,
  FlexColumnWidth,
  FractionColumnWidth,
  IntrinsicColumnWidth,
  MaxColumnWidth,
  MinColumnWidth,
  TableBorder,
  TableCellVerticalAlignment,
  TableColumnWidth;
Hixie's avatar
Hixie committed
25

26
/// A horizontal group of cells in a [Table].
27 28 29 30 31
///
/// Every row in a table must have the same number of children.
///
/// The alignment of individual cells in a row can be controlled using a
/// [TableCell].
32
@immutable
Hixie's avatar
Hixie committed
33
class TableRow {
34
  /// Creates a row in a [Table].
35
  const TableRow({ this.key, this.decoration, this.children });
36 37

  /// An identifier for the row.
38
  final LocalKey? key;
39 40 41 42 43 44

  /// A decoration to paint behind this row.
  ///
  /// Row decorations fill the horizontal and vertical extent of each row in
  /// the table, unlike decorations for individual cells, which might not fill
  /// either.
45
  final Decoration? decoration;
46 47 48 49 50 51

  /// The widgets that comprise the cells in this row.
  ///
  /// Children may be wrapped in [TableCell] widgets to provide per-cell
  /// configuration to the [Table], but children are not required to be wrapped
  /// in [TableCell] widgets.
52
  final List<Widget>? children;
53 54 55

  @override
  String toString() {
56
    final StringBuffer result = StringBuffer();
57
    result.write('TableRow(');
58
    if (key != null) {
59
      result.write('$key, ');
60 61
    }
    if (decoration != null) {
62
      result.write('$decoration, ');
63
    }
64
    if (children == null) {
65
      result.write('child list is null');
66
    } else if (children!.isEmpty) {
67 68 69 70 71 72 73
      result.write('no children');
    } else {
      result.write('$children');
    }
    result.write(')');
    return result.toString();
  }
Hixie's avatar
Hixie committed
74 75 76
}

class _TableElementRow {
77 78
  const _TableElementRow({ this.key, required this.children });
  final LocalKey? key;
Hixie's avatar
Hixie committed
79 80 81
  final List<Element> children;
}

82
/// A widget that uses the table layout algorithm for its children.
Hixie's avatar
Hixie committed
83
///
84 85
/// {@youtube 560 315 https://www.youtube.com/watch?v=_lbE0wsVZSw}
///
86
/// {@tool dartpad}
87 88
/// This sample shows a `Table` with borders, multiple types of column widths and different vertical cell alignments.
///
89
/// ** See code in examples/api/lib/widgets/table/table.0.dart **
90 91
/// {@end-tool}
///
92
/// If you only have one row, the [Row] widget is more appropriate. If you only
93 94
/// have one column, the [SliverList] or [Column] widgets will be more
/// appropriate.
95
///
96 97 98 99 100 101 102 103 104 105 106
/// Rows size vertically based on their contents. To control the individual
/// column widths, use the [columnWidths] property to specify a
/// [TableColumnWidth] for each column. If [columnWidths] is null, or there is a
/// null entry for a given column in [columnWidths], the table uses the
/// [defaultColumnWidth] instead.
///
/// By default, [defaultColumnWidth] is a [FlexColumnWidth]. This
/// [TableColumnWidth] divides up the remaining space in the horizontal axis to
/// determine the column width. If wrapping a [Table] in a horizontal
/// [ScrollView], choose a different [TableColumnWidth], such as
/// [FixedColumnWidth].
107 108
///
/// For more details about the table layout algorithm, see [RenderTable].
Hixie's avatar
Hixie committed
109
/// To control the alignment of children, see [TableCell].
110 111 112 113
///
/// See also:
///
///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
Hixie's avatar
Hixie committed
114
class Table extends RenderObjectWidget {
115 116 117 118
  /// Creates a table.
  ///
  /// The [children], [defaultColumnWidth], and [defaultVerticalAlignment]
  /// arguments must not be null.
Hixie's avatar
Hixie committed
119
  Table({
120
    super.key,
121
    this.children = const <TableRow>[],
Hixie's avatar
Hixie committed
122
    this.columnWidths,
123
    this.defaultColumnWidth = const FlexColumnWidth(),
124
    this.textDirection,
Hixie's avatar
Hixie committed
125
    this.border,
126
    this.defaultVerticalAlignment = TableCellVerticalAlignment.top,
127
    this.textBaseline, // NO DEFAULT: we don't know what the text's baseline should be
128 129 130
  }) : assert(children != null),
       assert(defaultColumnWidth != null),
       assert(defaultVerticalAlignment != null),
131
       assert(defaultVerticalAlignment != TableCellVerticalAlignment.baseline || textBaseline != null, 'textBaseline is required if you specify the defaultVerticalAlignment with TableCellVerticalAlignment.baseline'),
132 133 134 135
       assert(() {
         if (children.any((TableRow row) => row.children == null)) {
           throw FlutterError(
             'One of the rows of the table had null children.\n'
136
             'The children property of TableRow must not be null.',
137 138 139 140
           );
         }
         return true;
       }()),
141
       assert(() {
142
         if (children.any((TableRow row) => row.children!.any((Widget cell) => cell == null))) {
143
           throw FlutterError(
144
             'One of the children of one of the rows of the table was null.\n'
145
             'The children of a TableRow must not be null.',
146 147 148
           );
         }
         return true;
149
       }()),
150 151
       assert(() {
         if (children.any((TableRow row1) => row1.key != null && children.any((TableRow row2) => row1 != row2 && row1.key == row2.key))) {
152
           throw FlutterError(
153
             'Two or more TableRow children of this Table had the same key.\n'
154
             'All the keyed TableRow children of a Table must have different Keys.',
155 156 157
           );
         }
         return true;
158
       }()),
159 160
       assert(() {
         if (children.isNotEmpty) {
161 162
           final int cellCount = children.first.children!.length;
           if (children.any((TableRow row) => row.children!.length != cellCount)) {
163
             throw FlutterError(
164 165
               'Table contains irregular row lengths.\n'
               'Every TableRow in a Table must have the same number of children, so that every cell is filled. '
166
               'Otherwise, the table will contain holes.',
167 168 169 170
             );
           }
         }
         return true;
171
       }()),
172
       _rowDecorations = children.any((TableRow row) => row.decoration != null)
173
                              ? children.map<Decoration?>((TableRow row) => row.decoration).toList(growable: false)
174
                              : null {
Hixie's avatar
Hixie committed
175
    assert(() {
176
      final List<Widget> flatChildren = children.expand<Widget>((TableRow row) => row.children!).toList(growable: false);
177
      if (debugChildrenHaveDuplicateKeys(this, flatChildren)) {
178
        throw FlutterError(
179 180 181
          'Two or more cells in this Table contain widgets with the same key.\n'
          'Every widget child of every TableRow in a Table must have different keys. The cells of a Table are '
          'flattened out for processing, so separate cells cannot have duplicate keys even if they are in '
182
          'different rows.',
183 184 185
        );
      }
      return true;
186
    }());
Hixie's avatar
Hixie committed
187 188
  }

189
  /// The rows of the table.
190 191 192
  ///
  /// Every row in a table must have the same number of children, and all the
  /// children must be non-null.
Hixie's avatar
Hixie committed
193
  final List<TableRow> children;
194 195 196 197

  /// 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
198 199 200 201 202
  /// [defaultColumnWidth] instead. By default, that uses flex sizing to
  /// distribute free space equally among the columns.
  ///
  /// The [FixedColumnWidth] class can be used to specify a specific width in
  /// pixels. That is the cheapest way to size a table's columns.
203 204 205 206 207
  ///
  /// 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.
208 209
  ///
  /// The keys of this map (column indexes) are zero-based.
210 211
  ///
  /// If this is set to null, then an empty map is assumed.
212
  final Map<int, TableColumnWidth>? columnWidths;
213

214 215
  /// How to determine with widths of columns that don't have an explicit sizing
  /// algorithm.
216 217
  ///
  /// Specifically, the [defaultColumnWidth] is used for column `i` if
218 219 220 221 222 223
  /// `columnWidths[i]` is null. Defaults to [FlexColumnWidth], which will
  /// divide the remaining horizontal space up evenly between columns of the
  /// same type [TableColumnWidth].
  ///
  /// A [Table] in a horizontal [ScrollView] must use a [FixedColumnWidth], or
  /// an [IntrinsicColumnWidth] as the horizontal space is infinite.
Hixie's avatar
Hixie committed
224
  final TableColumnWidth defaultColumnWidth;
225

226 227 228
  /// The direction in which the columns are ordered.
  ///
  /// Defaults to the ambient [Directionality].
229
  final TextDirection? textDirection;
230

231
  /// The style to use when painting the boundary and interior divisions of the table.
232
  final TableBorder? border;
233 234

  /// How cells that do not explicitly specify a vertical alignment are aligned vertically.
235 236 237
  ///
  /// Cells may specify a vertical alignment by wrapping their contents in a
  /// [TableCell] widget.
Hixie's avatar
Hixie committed
238
  final TableCellVerticalAlignment defaultVerticalAlignment;
239 240

  /// The text baseline to use when aligning rows using [TableCellVerticalAlignment.baseline].
241
  ///
242 243 244
  /// This must be set if using baseline alignment. There is no default because there is no
  /// way for the framework to know the correct baseline _a priori_.
  final TextBaseline? textBaseline;
Hixie's avatar
Hixie committed
245

246
  final List<Decoration?>? _rowDecorations;
247

Hixie's avatar
Hixie committed
248
  @override
249
  RenderObjectElement createElement() => _TableElement(this);
Hixie's avatar
Hixie committed
250 251 252

  @override
  RenderTable createRenderObject(BuildContext context) {
253
    assert(debugCheckHasDirectionality(context));
254
    return RenderTable(
255
      columns: children.isNotEmpty ? children[0].children!.length : 0,
Hixie's avatar
Hixie committed
256 257 258
      rows: children.length,
      columnWidths: columnWidths,
      defaultColumnWidth: defaultColumnWidth,
259
      textDirection: textDirection ?? Directionality.of(context),
Hixie's avatar
Hixie committed
260
      border: border,
261
      rowDecorations: _rowDecorations,
262
      configuration: createLocalImageConfiguration(context),
Hixie's avatar
Hixie committed
263
      defaultVerticalAlignment: defaultVerticalAlignment,
264
      textBaseline: textBaseline,
Hixie's avatar
Hixie committed
265 266 267 268 269
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderTable renderObject) {
270
    assert(debugCheckHasDirectionality(context));
271
    assert(renderObject.columns == (children.isNotEmpty ? children[0].children!.length : 0));
Hixie's avatar
Hixie committed
272 273 274 275
    assert(renderObject.rows == children.length);
    renderObject
      ..columnWidths = columnWidths
      ..defaultColumnWidth = defaultColumnWidth
276
      ..textDirection = textDirection ?? Directionality.of(context)
Hixie's avatar
Hixie committed
277
      ..border = border
278
      ..rowDecorations = _rowDecorations
279
      ..configuration = createLocalImageConfiguration(context)
Hixie's avatar
Hixie committed
280 281 282 283 284 285
      ..defaultVerticalAlignment = defaultVerticalAlignment
      ..textBaseline = textBaseline;
  }
}

class _TableElement extends RenderObjectElement {
286
  _TableElement(Table super.widget);
Hixie's avatar
Hixie committed
287 288

  @override
289
  RenderTable get renderObject => super.renderObject as RenderTable;
Hixie's avatar
Hixie committed
290 291 292

  List<_TableElementRow> _children = const<_TableElementRow>[];

293 294
  bool _doingMountOrUpdate = false;

Hixie's avatar
Hixie committed
295
  @override
296 297 298
  void mount(Element? parent, Object? newSlot) {
    assert(!_doingMountOrUpdate);
    _doingMountOrUpdate = true;
Hixie's avatar
Hixie committed
299
    super.mount(parent, newSlot);
300
    int rowIndex = -1;
301
    _children = (widget as Table).children.map<_TableElementRow>((TableRow row) {
302 303
      int columnIndex = 0;
      rowIndex += 1;
304
      return _TableElementRow(
Hixie's avatar
Hixie committed
305
        key: row.key,
306
        children: row.children!.map<Element>((Widget child) {
307
          assert(child != null);
308
          return inflateWidget(child, _TableSlot(columnIndex++, rowIndex));
309
        }).toList(growable: false),
Hixie's avatar
Hixie committed
310 311 312
      );
    }).toList(growable: false);
    _updateRenderObjectChildren();
313 314
    assert(_doingMountOrUpdate);
    _doingMountOrUpdate = false;
Hixie's avatar
Hixie committed
315 316 317
  }

  @override
318
  void insertRenderObjectChild(RenderBox child, _TableSlot slot) {
Hixie's avatar
Hixie committed
319
    renderObject.setupParentData(child);
320 321 322 323 324
    // Once [mount]/[update] are done, the children are getting set all at once
    // in [_updateRenderObjectChildren].
    if (!_doingMountOrUpdate) {
      renderObject.setChild(slot.column, slot.row, child);
    }
Hixie's avatar
Hixie committed
325 326 327
  }

  @override
328 329 330
  void moveRenderObjectChild(RenderBox child, _TableSlot oldSlot, _TableSlot newSlot) {
    assert(_doingMountOrUpdate);
    // Child gets moved at the end of [update] in [_updateRenderObjectChildren].
Hixie's avatar
Hixie committed
331 332 333
  }

  @override
334
  void removeRenderObjectChild(RenderBox child, _TableSlot slot) {
335
    renderObject.setChild(slot.column, slot.row, null);
Hixie's avatar
Hixie committed
336 337
  }

338
  final Set<Element> _forgottenChildren = HashSet<Element>();
Hixie's avatar
Hixie committed
339 340 341

  @override
  void update(Table newWidget) {
342 343
    assert(!_doingMountOrUpdate);
    _doingMountOrUpdate = true;
344
    final Map<LocalKey, List<Element>> oldKeyedRows = <LocalKey, List<Element>>{};
345
    for (final _TableElementRow row in _children) {
346
      if (row.key != null) {
347
        oldKeyedRows[row.key!] = row.children;
348 349
      }
    }
350 351
    final Iterator<_TableElementRow> oldUnkeyedRows = _children.where((_TableElementRow row) => row.key == null).iterator;
    final List<_TableElementRow> newChildren = <_TableElementRow>[];
352
    final Set<List<Element>> taken = <List<Element>>{};
353 354
    for (int rowIndex = 0; rowIndex < newWidget.children.length; rowIndex++) {
      final TableRow row = newWidget.children[rowIndex];
Hixie's avatar
Hixie committed
355 356
      List<Element> oldChildren;
      if (row.key != null && oldKeyedRows.containsKey(row.key)) {
357
        oldChildren = oldKeyedRows[row.key]!;
Hixie's avatar
Hixie committed
358 359 360 361 362 363
        taken.add(oldChildren);
      } else if (row.key == null && oldUnkeyedRows.moveNext()) {
        oldChildren = oldUnkeyedRows.current.children;
      } else {
        oldChildren = const <Element>[];
      }
364 365 366 367
      final List<_TableSlot> slots = List<_TableSlot>.generate(
        row.children!.length,
        (int columnIndex) => _TableSlot(columnIndex, rowIndex),
      );
368
      newChildren.add(_TableElementRow(
Hixie's avatar
Hixie committed
369
        key: row.key,
370
        children: updateChildren(oldChildren, row.children!, forgottenChildren: _forgottenChildren, slots: slots),
Hixie's avatar
Hixie committed
371 372
      ));
    }
373
    while (oldUnkeyedRows.moveNext()) {
374
      updateChildren(oldUnkeyedRows.current.children, const <Widget>[], forgottenChildren: _forgottenChildren);
375 376
    }
    for (final List<Element> oldChildren in oldKeyedRows.values.where((List<Element> list) => !taken.contains(list))) {
377
      updateChildren(oldChildren, const <Widget>[], forgottenChildren: _forgottenChildren);
378
    }
379

Hixie's avatar
Hixie committed
380 381
    _children = newChildren;
    _updateRenderObjectChildren();
382
    _forgottenChildren.clear();
Hixie's avatar
Hixie committed
383 384
    super.update(newWidget);
    assert(widget == newWidget);
385 386
    assert(_doingMountOrUpdate);
    _doingMountOrUpdate = false;
Hixie's avatar
Hixie committed
387 388 389 390 391
  }

  void _updateRenderObjectChildren() {
    assert(renderObject != null);
    renderObject.setFlatChildren(
392
      _children.isNotEmpty ? _children[0].children.length : 0,
393 394
      _children.expand<RenderBox>((_TableElementRow row) {
        return row.children.map<RenderBox>((Element child) {
395
          final RenderBox box = child.renderObject! as RenderBox;
396 397
          return box;
        });
398
      }).toList(),
Hixie's avatar
Hixie committed
399 400 401 402 403
    );
  }

  @override
  void visitChildren(ElementVisitor visitor) {
404
    for (final Element child in _children.expand<Element>((_TableElementRow row) => row.children)) {
405
      if (!_forgottenChildren.contains(child)) {
Hixie's avatar
Hixie committed
406
        visitor(child);
407
      }
Hixie's avatar
Hixie committed
408 409 410 411
    }
  }

  @override
412 413
  bool forgetChild(Element child) {
    _forgottenChildren.add(child);
414
    super.forgetChild(child);
Hixie's avatar
Hixie committed
415 416 417 418
    return true;
  }
}

419 420 421 422 423 424
/// A widget that controls how a child of a [Table] is aligned.
///
/// A [TableCell] widget must be a descendant of a [Table], and the path from
/// the [TableCell] widget to its enclosing [Table] must contain only
/// [TableRow]s, [StatelessWidget]s, or [StatefulWidget]s (not
/// other kinds of widgets, like [RenderObjectWidget]s).
425
class TableCell extends ParentDataWidget<TableCellParentData> {
426
  /// Creates a widget that controls how a child of a [Table] is aligned.
427
  const TableCell({
428
    super.key,
429
    this.verticalAlignment,
430 431
    required super.child,
  });
Hixie's avatar
Hixie committed
432

433
  /// How this cell is aligned vertically.
434
  final TableCellVerticalAlignment? verticalAlignment;
Hixie's avatar
Hixie committed
435 436 437

  @override
  void applyParentData(RenderObject renderObject) {
438
    final TableCellParentData parentData = renderObject.parentData! as TableCellParentData;
Hixie's avatar
Hixie committed
439 440
    if (parentData.verticalAlignment != verticalAlignment) {
      parentData.verticalAlignment = verticalAlignment;
441
      final AbstractNode? targetParent = renderObject.parent;
442
      if (targetParent is RenderObject) {
Hixie's avatar
Hixie committed
443
        targetParent.markNeedsLayout();
444
      }
Hixie's avatar
Hixie committed
445 446 447
    }
  }

448 449 450
  @override
  Type get debugTypicalAncestorWidgetClass => Table;

Hixie's avatar
Hixie committed
451
  @override
452 453
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
454
    properties.add(EnumProperty<TableCellVerticalAlignment>('verticalAlignment', verticalAlignment));
Hixie's avatar
Hixie committed
455 456
  }
}
457 458 459 460 461 462 463 464 465 466

@immutable
class _TableSlot with Diagnosticable {
  const _TableSlot(this.column, this.row);

  final int column;
  final int row;

  @override
  bool operator ==(Object other) {
467
    if (other.runtimeType != runtimeType) {
468
      return false;
469
    }
470 471 472 473 474 475
    return other is _TableSlot
        && column == other.column
        && row == other.row;
  }

  @override
476
  int get hashCode => Object.hash(column, row);
477 478 479 480 481 482 483 484

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(IntProperty('x', column));
    properties.add(IntProperty('y', row));
  }
}