table.dart 13.4 KB
Newer Older
Hixie's avatar
Hixie committed
1 2 3 4 5 6
// Copyright 2015 The Chromium Authors. All rights reserved.
// 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 93
/// To control the alignment of children, see [TableCell].
class Table extends RenderObjectWidget {
94 95 96 97
  /// Creates a table.
  ///
  /// The [children], [defaultColumnWidth], and [defaultVerticalAlignment]
  /// arguments must not be null.
Hixie's avatar
Hixie committed
98 99
  Table({
    Key key,
100
    this.children = const <TableRow>[],
Hixie's avatar
Hixie committed
101
    this.columnWidths,
102
    this.defaultColumnWidth = const FlexColumnWidth(1.0),
103
    this.textDirection,
Hixie's avatar
Hixie committed
104
    this.border,
105
    this.defaultVerticalAlignment = TableCellVerticalAlignment.top,
106
    this.textBaseline,
107 108 109 110 111
  }) : assert(children != null),
       assert(defaultColumnWidth != null),
       assert(defaultVerticalAlignment != null),
       assert(() {
         if (children.any((TableRow row) => row.children.any((Widget cell) => cell == null))) {
112
           throw FlutterError(
113 114 115 116 117
             '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;
118
       }()),
119 120
       assert(() {
         if (children.any((TableRow row1) => row1.key != null && children.any((TableRow row2) => row1 != row2 && row1.key == row2.key))) {
121
           throw FlutterError(
122 123 124 125 126
             '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;
127
       }()),
128 129 130 131
       assert(() {
         if (children.isNotEmpty) {
           final int cellCount = children.first.children.length;
           if (children.any((TableRow row) => row.children.length != cellCount)) {
132
             throw FlutterError(
133 134 135 136 137 138 139
               '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;
140
       }()),
141 142 143
       _rowDecorations = children.any((TableRow row) => row.decoration != null)
                              ? children.map<Decoration>((TableRow row) => row.decoration).toList(growable: false)
                              : null,
144
       super(key: key) {
Hixie's avatar
Hixie committed
145
    assert(() {
146
      final List<Widget> flatChildren = children.expand<Widget>((TableRow row) => row.children).toList(growable: false);
147
      if (debugChildrenHaveDuplicateKeys(this, flatChildren)) {
148
        throw FlutterError(
149 150 151 152 153 154 155
          '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;
156
    }());
Hixie's avatar
Hixie committed
157 158
  }

159
  /// The rows of the table.
160 161 162
  ///
  /// 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
163
  final List<TableRow> children;
164 165 166 167

  /// 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
168 169 170 171 172
  /// [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.
173 174 175 176 177
  ///
  /// 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
178
  final Map<int, TableColumnWidth> columnWidths;
179 180 181 182 183

  /// 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
184
  final TableColumnWidth defaultColumnWidth;
185

186 187 188 189 190
  /// The direction in which the columns are ordered.
  ///
  /// Defaults to the ambient [Directionality].
  final TextDirection textDirection;

191
  /// The style to use when painting the boundary and interior divisions of the table.
Hixie's avatar
Hixie committed
192
  final TableBorder border;
193 194

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

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

200 201
  final List<Decoration> _rowDecorations;

Hixie's avatar
Hixie committed
202
  @override
203
  _TableElement createElement() => _TableElement(this);
Hixie's avatar
Hixie committed
204 205 206

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

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

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

  @override
  Table get widget => super.widget;

  @override
  RenderTable get renderObject => super.renderObject;

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

  @override
  void insertChildRenderObject(RenderObject child, Element slot) {
    renderObject.setupParentData(child);
  }

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

  @override
  void removeChildRenderObject(RenderObject child) {
279
    final TableCellParentData childParentData = child.parentData;
Hixie's avatar
Hixie committed
280 281 282
    renderObject.setChild(childParentData.x, childParentData.y, null);
  }

283
  final Set<Element> _forgottenChildren = HashSet<Element>();
Hixie's avatar
Hixie committed
284 285 286

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

Hixie's avatar
Hixie committed
316 317
    _children = newChildren;
    _updateRenderObjectChildren();
318
    _forgottenChildren.clear();
Hixie's avatar
Hixie committed
319 320 321 322 323 324 325
    super.update(newWidget);
    assert(widget == newWidget);
  }

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

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

  @override
345 346
  bool forgetChild(Element child) {
    _forgottenChildren.add(child);
Hixie's avatar
Hixie committed
347 348 349 350
    return true;
  }
}

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

365
  /// How this cell is aligned vertically.
Hixie's avatar
Hixie committed
366 367 368 369 370 371 372
  final TableCellVerticalAlignment verticalAlignment;

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

  @override
380 381
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
382
    properties.add(EnumProperty<TableCellVerticalAlignment>('verticalAlignment', verticalAlignment));
Hixie's avatar
Hixie committed
383 384
  }
}