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

5 6
// @dart = 2.8

Hixie's avatar
Hixie committed
7 8
import 'dart:collection';

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

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

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

28
/// A horizontal group of cells in a [Table].
29 30 31 32 33
///
/// 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].
34
@immutable
Hixie's avatar
Hixie committed
35
class TableRow {
36
  /// Creates a row in a [Table].
37
  const TableRow({ this.key, this.decoration, this.children });
38 39

  /// An identifier for the row.
Hixie's avatar
Hixie committed
40
  final LocalKey key;
41 42 43 44 45 46

  /// 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.
47
  final Decoration decoration;
48 49 50 51 52 53

  /// 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
54
  final List<Widget> children;
55 56 57

  @override
  String toString() {
58
    final StringBuffer result = StringBuffer();
59 60 61 62 63
    result.write('TableRow(');
    if (key != null)
      result.write('$key, ');
    if (decoration != null)
      result.write('$decoration, ');
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 77 78 79 80 81
}

class _TableElementRow {
  const _TableElementRow({ this.key, this.children });
  final LocalKey key;
  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
/// If you only have one row, the [Row] widget is more appropriate. If you only
87 88
/// have one column, the [SliverList] or [Column] widgets will be more
/// appropriate.
89 90 91 92 93
///
/// 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
94
/// To control the alignment of children, see [TableCell].
95 96 97 98
///
/// See also:
///
///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
Hixie's avatar
Hixie committed
99
class Table extends RenderObjectWidget {
100 101 102 103
  /// Creates a table.
  ///
  /// The [children], [defaultColumnWidth], and [defaultVerticalAlignment]
  /// arguments must not be null.
Hixie's avatar
Hixie committed
104 105
  Table({
    Key key,
106
    this.children = const <TableRow>[],
Hixie's avatar
Hixie committed
107
    this.columnWidths,
108
    this.defaultColumnWidth = const FlexColumnWidth(1.0),
109
    this.textDirection,
Hixie's avatar
Hixie committed
110
    this.border,
111
    this.defaultVerticalAlignment = TableCellVerticalAlignment.top,
112
    this.textBaseline,
113 114 115 116 117
  }) : assert(children != null),
       assert(defaultColumnWidth != null),
       assert(defaultVerticalAlignment != null),
       assert(() {
         if (children.any((TableRow row) => row.children.any((Widget cell) => cell == null))) {
118
           throw FlutterError(
119 120 121 122 123
             '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;
124
       }()),
125 126
       assert(() {
         if (children.any((TableRow row1) => row1.key != null && children.any((TableRow row2) => row1 != row2 && row1.key == row2.key))) {
127
           throw FlutterError(
128 129 130 131 132
             '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;
133
       }()),
134 135 136 137
       assert(() {
         if (children.isNotEmpty) {
           final int cellCount = children.first.children.length;
           if (children.any((TableRow row) => row.children.length != cellCount)) {
138
             throw FlutterError(
139 140 141 142 143 144 145
               '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;
146
       }()),
147 148 149
       _rowDecorations = children.any((TableRow row) => row.decoration != null)
                              ? children.map<Decoration>((TableRow row) => row.decoration).toList(growable: false)
                              : null,
150
       super(key: key) {
Hixie's avatar
Hixie committed
151
    assert(() {
152
      final List<Widget> flatChildren = children.expand<Widget>((TableRow row) => row.children).toList(growable: false);
153
      if (debugChildrenHaveDuplicateKeys(this, flatChildren)) {
154
        throw FlutterError(
155 156 157 158 159 160 161
          '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;
162
    }());
Hixie's avatar
Hixie committed
163 164
  }

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

  /// 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
174 175 176 177 178
  /// [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.
179 180 181 182 183
  ///
  /// 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
184
  final Map<int, TableColumnWidth> columnWidths;
185 186 187 188 189

  /// 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
190
  final TableColumnWidth defaultColumnWidth;
191

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

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

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

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

206 207
  final List<Decoration> _rowDecorations;

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

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

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

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

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

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

  // 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);
262
    _children = widget.children.map<_TableElementRow>((TableRow row) {
263
      return _TableElementRow(
Hixie's avatar
Hixie committed
264
        key: row.key,
265
        children: row.children.map<Element>((Widget child) {
266 267
          assert(child != null);
          return inflateWidget(child, null);
268
        }).toList(growable: false),
Hixie's avatar
Hixie committed
269 270 271 272 273 274
      );
    }).toList(growable: false);
    _updateRenderObjectChildren();
  }

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

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

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

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

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

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

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

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

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

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

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

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

386 387 388
  @override
  Type get debugTypicalAncestorWidgetClass => Table;

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