table.dart 13.7 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.
Hixie's avatar
Hixie committed
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.
Hixie's avatar
Hixie committed
52
  final List<Widget> children;
53 54 55

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

class _TableElementRow {
  const _TableElementRow({ this.key, this.children });
  final LocalKey key;
  final List<Element> children;
}

80
/// A widget that uses the table layout algorithm for its children.
Hixie's avatar
Hixie committed
81
///
82 83
/// {@youtube 560 315 https://www.youtube.com/watch?v=_lbE0wsVZSw}
///
84
/// If you only have one row, the [Row] widget is more appropriate. If you only
85 86
/// have one column, the [SliverList] or [Column] widgets will be more
/// appropriate.
87 88 89 90 91
///
/// Rows size vertically based on their contents. To control the column widths,
/// use the [columnWidths] property.
///
/// For more details about the table layout algorithm, see [RenderTable].
Hixie's avatar
Hixie committed
92
/// To control the alignment of children, see [TableCell].
93 94 95 96
///
/// See also:
///
///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
Hixie's avatar
Hixie committed
97
class Table extends RenderObjectWidget {
98 99 100 101
  /// Creates a table.
  ///
  /// The [children], [defaultColumnWidth], and [defaultVerticalAlignment]
  /// arguments must not be null.
Hixie's avatar
Hixie committed
102 103
  Table({
    Key key,
104
    this.children = const <TableRow>[],
Hixie's avatar
Hixie committed
105
    this.columnWidths,
106
    this.defaultColumnWidth = const FlexColumnWidth(1.0),
107
    this.textDirection,
Hixie's avatar
Hixie committed
108
    this.border,
109
    this.defaultVerticalAlignment = TableCellVerticalAlignment.top,
110
    this.textBaseline,
111 112 113 114 115
  }) : assert(children != null),
       assert(defaultColumnWidth != null),
       assert(defaultVerticalAlignment != null),
       assert(() {
         if (children.any((TableRow row) => row.children.any((Widget cell) => cell == null))) {
116
           throw FlutterError(
117 118 119 120 121
             'One of the children of one of the rows of the table was null.\n'
             'The children of a TableRow must not be null.'
           );
         }
         return true;
122
       }()),
123 124
       assert(() {
         if (children.any((TableRow row1) => row1.key != null && children.any((TableRow row2) => row1 != row2 && row1.key == row2.key))) {
125
           throw FlutterError(
126 127 128 129 130
             'Two or more TableRow children of this Table had the same key.\n'
             'All the keyed TableRow children of a Table must have different Keys.'
           );
         }
         return true;
131
       }()),
132 133 134 135
       assert(() {
         if (children.isNotEmpty) {
           final int cellCount = children.first.children.length;
           if (children.any((TableRow row) => row.children.length != cellCount)) {
136
             throw FlutterError(
137 138 139 140 141 142 143
               'Table contains irregular row lengths.\n'
               'Every TableRow in a Table must have the same number of children, so that every cell is filled. '
               'Otherwise, the table will contain holes.'
             );
           }
         }
         return true;
144
       }()),
145 146 147
       _rowDecorations = children.any((TableRow row) => row.decoration != null)
                              ? children.map<Decoration>((TableRow row) => row.decoration).toList(growable: false)
                              : null,
148
       super(key: key) {
Hixie's avatar
Hixie committed
149
    assert(() {
150
      final List<Widget> flatChildren = children.expand<Widget>((TableRow row) => row.children).toList(growable: false);
151
      if (debugChildrenHaveDuplicateKeys(this, flatChildren)) {
152
        throw FlutterError(
153 154 155 156 157 158 159
          '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 '
          'different rows.'
        );
      }
      return true;
160
    }());
Hixie's avatar
Hixie committed
161 162
  }

163
  /// The rows of the table.
164 165 166
  ///
  /// 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
167
  final List<TableRow> children;
168 169 170 171

  /// 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
172 173 174 175 176
  /// [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.
177 178 179 180 181
  ///
  /// 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.
Hixie's avatar
Hixie committed
182
  final Map<int, TableColumnWidth> columnWidths;
183 184 185 186 187

  /// 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
188
  final TableColumnWidth defaultColumnWidth;
189

190 191 192 193 194
  /// The direction in which the columns are ordered.
  ///
  /// Defaults to the ambient [Directionality].
  final TextDirection textDirection;

195
  /// The style to use when painting the boundary and interior divisions of the table.
Hixie's avatar
Hixie committed
196
  final TableBorder border;
197 198

  /// How cells that do not explicitly specify a vertical alignment are aligned vertically.
Hixie's avatar
Hixie committed
199
  final TableCellVerticalAlignment defaultVerticalAlignment;
200 201

  /// The text baseline to use when aligning rows using [TableCellVerticalAlignment.baseline].
Hixie's avatar
Hixie committed
202 203
  final TextBaseline textBaseline;

204 205
  final List<Decoration> _rowDecorations;

Hixie's avatar
Hixie committed
206
  @override
207
  _TableElement createElement() => _TableElement(this);
Hixie's avatar
Hixie committed
208 209 210

  @override
  RenderTable createRenderObject(BuildContext context) {
211
    assert(debugCheckHasDirectionality(context));
212
    return RenderTable(
213
      columns: children.isNotEmpty ? children[0].children.length : 0,
Hixie's avatar
Hixie committed
214 215 216
      rows: children.length,
      columnWidths: columnWidths,
      defaultColumnWidth: defaultColumnWidth,
217
      textDirection: textDirection ?? Directionality.of(context),
Hixie's avatar
Hixie committed
218
      border: border,
219
      rowDecorations: _rowDecorations,
220
      configuration: createLocalImageConfiguration(context),
Hixie's avatar
Hixie committed
221
      defaultVerticalAlignment: defaultVerticalAlignment,
222
      textBaseline: textBaseline,
Hixie's avatar
Hixie committed
223 224 225 226 227
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderTable renderObject) {
228
    assert(debugCheckHasDirectionality(context));
229
    assert(renderObject.columns == (children.isNotEmpty ? children[0].children.length : 0));
Hixie's avatar
Hixie committed
230 231 232 233
    assert(renderObject.rows == children.length);
    renderObject
      ..columnWidths = columnWidths
      ..defaultColumnWidth = defaultColumnWidth
234
      ..textDirection = textDirection ?? Directionality.of(context)
Hixie's avatar
Hixie committed
235
      ..border = border
236
      ..rowDecorations = _rowDecorations
237
      ..configuration = createLocalImageConfiguration(context)
Hixie's avatar
Hixie committed
238 239 240 241 242 243 244 245 246
      ..defaultVerticalAlignment = defaultVerticalAlignment
      ..textBaseline = textBaseline;
  }
}

class _TableElement extends RenderObjectElement {
  _TableElement(Table widget) : super(widget);

  @override
247
  Table get widget => super.widget as Table;
Hixie's avatar
Hixie committed
248 249

  @override
250
  RenderTable get renderObject => super.renderObject as RenderTable;
Hixie's avatar
Hixie committed
251 252 253 254 255 256 257 258 259

  // This class ignores the child's slot entirely.
  // Instead of doing incremental updates to the child list, it replaces the entire list each frame.

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

  @override
  void mount(Element parent, dynamic newSlot) {
    super.mount(parent, newSlot);
260
    _children = widget.children.map<_TableElementRow>((TableRow row) {
261
      return _TableElementRow(
Hixie's avatar
Hixie committed
262
        key: row.key,
263
        children: row.children.map<Element>((Widget child) {
264 265
          assert(child != null);
          return inflateWidget(child, null);
266
        }).toList(growable: false),
Hixie's avatar
Hixie committed
267 268 269 270 271 272
      );
    }).toList(growable: false);
    _updateRenderObjectChildren();
  }

  @override
273
  void insertChildRenderObject(RenderObject child, IndexedSlot<Element> slot) {
Hixie's avatar
Hixie committed
274 275 276 277 278 279 280 281 282
    renderObject.setupParentData(child);
  }

  @override
  void moveChildRenderObject(RenderObject child, dynamic slot) {
  }

  @override
  void removeChildRenderObject(RenderObject child) {
283
    final TableCellParentData childParentData = child.parentData as TableCellParentData;
Hixie's avatar
Hixie committed
284 285 286
    renderObject.setChild(childParentData.x, childParentData.y, null);
  }

287
  final Set<Element> _forgottenChildren = HashSet<Element>();
Hixie's avatar
Hixie committed
288 289 290

  @override
  void update(Table newWidget) {
291
    final Map<LocalKey, List<Element>> oldKeyedRows = <LocalKey, List<Element>>{};
292
    for (final _TableElementRow row in _children) {
293 294 295 296
      if (row.key != null) {
        oldKeyedRows[row.key] = row.children;
      }
    }
297 298
    final Iterator<_TableElementRow> oldUnkeyedRows = _children.where((_TableElementRow row) => row.key == null).iterator;
    final List<_TableElementRow> newChildren = <_TableElementRow>[];
299
    final Set<List<Element>> taken = <List<Element>>{};
300
    for (final TableRow row in newWidget.children) {
Hixie's avatar
Hixie committed
301 302 303 304 305 306 307 308 309
      List<Element> oldChildren;
      if (row.key != null && oldKeyedRows.containsKey(row.key)) {
        oldChildren = oldKeyedRows[row.key];
        taken.add(oldChildren);
      } else if (row.key == null && oldUnkeyedRows.moveNext()) {
        oldChildren = oldUnkeyedRows.current.children;
      } else {
        oldChildren = const <Element>[];
      }
310
      newChildren.add(_TableElementRow(
Hixie's avatar
Hixie committed
311
        key: row.key,
312
        children: updateChildren(oldChildren, row.children, forgottenChildren: _forgottenChildren),
Hixie's avatar
Hixie committed
313 314 315
      ));
    }
    while (oldUnkeyedRows.moveNext())
316
      updateChildren(oldUnkeyedRows.current.children, const <Widget>[], forgottenChildren: _forgottenChildren);
317
    for (final List<Element> oldChildren in oldKeyedRows.values.where((List<Element> list) => !taken.contains(list)))
318
      updateChildren(oldChildren, const <Widget>[], forgottenChildren: _forgottenChildren);
319

Hixie's avatar
Hixie committed
320 321
    _children = newChildren;
    _updateRenderObjectChildren();
322
    _forgottenChildren.clear();
Hixie's avatar
Hixie committed
323 324 325 326 327 328 329
    super.update(newWidget);
    assert(widget == newWidget);
  }

  void _updateRenderObjectChildren() {
    assert(renderObject != null);
    renderObject.setFlatChildren(
330
      _children.isNotEmpty ? _children[0].children.length : 0,
331 332
      _children.expand<RenderBox>((_TableElementRow row) {
        return row.children.map<RenderBox>((Element child) {
333
          final RenderBox box = child.renderObject as RenderBox;
334 335
          return box;
        });
336
      }).toList(),
Hixie's avatar
Hixie committed
337 338 339 340 341
    );
  }

  @override
  void visitChildren(ElementVisitor visitor) {
342
    for (final Element child in _children.expand<Element>((_TableElementRow row) => row.children)) {
343
      if (!_forgottenChildren.contains(child))
Hixie's avatar
Hixie committed
344 345 346 347 348
        visitor(child);
    }
  }

  @override
349 350
  bool forgetChild(Element child) {
    _forgottenChildren.add(child);
351
    super.forgetChild(child);
Hixie's avatar
Hixie committed
352 353 354 355
    return true;
  }
}

356 357 358 359 360 361
/// 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).
362
class TableCell extends ParentDataWidget<TableCellParentData> {
363
  /// Creates a widget that controls how a child of a [Table] is aligned.
364
  const TableCell({
365 366
    Key key,
    this.verticalAlignment,
367
    @required Widget child,
368
  }) : super(key: key, child: child);
Hixie's avatar
Hixie committed
369

370
  /// How this cell is aligned vertically.
Hixie's avatar
Hixie committed
371 372 373 374
  final TableCellVerticalAlignment verticalAlignment;

  @override
  void applyParentData(RenderObject renderObject) {
375
    final TableCellParentData parentData = renderObject.parentData as TableCellParentData;
Hixie's avatar
Hixie committed
376 377
    if (parentData.verticalAlignment != verticalAlignment) {
      parentData.verticalAlignment = verticalAlignment;
378
      final AbstractNode targetParent = renderObject.parent;
Hixie's avatar
Hixie committed
379 380 381 382 383
      if (targetParent is RenderObject)
        targetParent.markNeedsLayout();
    }
  }

384 385 386
  @override
  Type get debugTypicalAncestorWidgetClass => Table;

Hixie's avatar
Hixie committed
387
  @override
388 389
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
390
    properties.add(EnumProperty<TableCellVerticalAlignment>('verticalAlignment', verticalAlignment));
Hixie's avatar
Hixie committed
391 392
  }
}