table.dart 15.2 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 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
}

class _TableElementRow {
75 76
  const _TableElementRow({ this.key, required this.children });
  final LocalKey? key;
Hixie's avatar
Hixie committed
77 78 79
  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 92 93 94 95 96 97 98
/// 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].
99 100
///
/// For more details about the table layout algorithm, see [RenderTable].
Hixie's avatar
Hixie committed
101
/// To control the alignment of children, see [TableCell].
102 103 104 105
///
/// See also:
///
///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
Hixie's avatar
Hixie committed
106
class Table extends RenderObjectWidget {
107 108 109 110
  /// Creates a table.
  ///
  /// The [children], [defaultColumnWidth], and [defaultVerticalAlignment]
  /// arguments must not be null.
Hixie's avatar
Hixie committed
111
  Table({
112
    Key? key,
113
    this.children = const <TableRow>[],
Hixie's avatar
Hixie committed
114
    this.columnWidths,
115
    this.defaultColumnWidth = const FlexColumnWidth(1.0),
116
    this.textDirection,
Hixie's avatar
Hixie committed
117
    this.border,
118
    this.defaultVerticalAlignment = TableCellVerticalAlignment.top,
119
    this.textBaseline = TextBaseline.alphabetic,
120 121 122
  }) : assert(children != null),
       assert(defaultColumnWidth != null),
       assert(defaultVerticalAlignment != null),
123 124 125 126 127 128 129 130 131
       assert(() {
         if (children.any((TableRow row) => row.children == null)) {
           throw FlutterError(
             'One of the rows of the table had null children.\n'
             'The children property of TableRow must not be null.'
           );
         }
         return true;
       }()),
132
       assert(() {
133
         if (children.any((TableRow row) => row.children!.any((Widget cell) => cell == null))) {
134
           throw FlutterError(
135 136 137 138 139
             '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;
140
       }()),
141 142
       assert(() {
         if (children.any((TableRow row1) => row1.key != null && children.any((TableRow row2) => row1 != row2 && row1.key == row2.key))) {
143
           throw FlutterError(
144 145 146 147 148
             '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;
149
       }()),
150 151
       assert(() {
         if (children.isNotEmpty) {
152 153
           final int cellCount = children.first.children!.length;
           if (children.any((TableRow row) => row.children!.length != cellCount)) {
154
             throw FlutterError(
155 156 157 158 159 160 161
               '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;
162
       }()),
163
       _rowDecorations = children.any((TableRow row) => row.decoration != null)
164
                              ? children.map<Decoration?>((TableRow row) => row.decoration).toList(growable: false)
165
                              : null,
166
       super(key: key) {
Hixie's avatar
Hixie committed
167
    assert(() {
168
      final List<Widget> flatChildren = children.expand<Widget>((TableRow row) => row.children!).toList(growable: false);
169
      if (debugChildrenHaveDuplicateKeys(this, flatChildren)) {
170
        throw FlutterError(
171 172 173 174 175 176 177
          '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;
178
    }());
Hixie's avatar
Hixie committed
179 180
  }

181
  /// The rows of the table.
182 183 184
  ///
  /// 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
185
  final List<TableRow> children;
186 187 188 189

  /// 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
190 191 192 193 194
  /// [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.
195 196 197 198 199
  ///
  /// 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.
200 201
  ///
  /// The keys of this map (column indexes) are zero-based.
202 203
  ///
  /// If this is set to null, then an empty map is assumed.
204
  final Map<int, TableColumnWidth>? columnWidths;
205

206 207
  /// How to determine with widths of columns that don't have an explicit sizing
  /// algorithm.
208 209
  ///
  /// Specifically, the [defaultColumnWidth] is used for column `i` if
210 211 212 213 214 215
  /// `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
216
  final TableColumnWidth defaultColumnWidth;
217

218 219 220
  /// The direction in which the columns are ordered.
  ///
  /// Defaults to the ambient [Directionality].
221
  final TextDirection? textDirection;
222

223
  /// The style to use when painting the boundary and interior divisions of the table.
224
  final TableBorder? border;
225 226

  /// How cells that do not explicitly specify a vertical alignment are aligned vertically.
227 228 229
  ///
  /// Cells may specify a vertical alignment by wrapping their contents in a
  /// [TableCell] widget.
Hixie's avatar
Hixie committed
230
  final TableCellVerticalAlignment defaultVerticalAlignment;
231 232

  /// The text baseline to use when aligning rows using [TableCellVerticalAlignment.baseline].
233 234
  ///
  /// Defaults to [TextBaseline.alphabetic].
Hixie's avatar
Hixie committed
235 236
  final TextBaseline textBaseline;

237
  final List<Decoration?>? _rowDecorations;
238

Hixie's avatar
Hixie committed
239
  @override
240
  _TableElement createElement() => _TableElement(this);
Hixie's avatar
Hixie committed
241 242 243

  @override
  RenderTable createRenderObject(BuildContext context) {
244
    assert(debugCheckHasDirectionality(context));
245
    return RenderTable(
246
      columns: children.isNotEmpty ? children[0].children!.length : 0,
Hixie's avatar
Hixie committed
247 248 249
      rows: children.length,
      columnWidths: columnWidths,
      defaultColumnWidth: defaultColumnWidth,
250
      textDirection: textDirection ?? Directionality.of(context)!,
Hixie's avatar
Hixie committed
251
      border: border,
252
      rowDecorations: _rowDecorations,
253
      configuration: createLocalImageConfiguration(context),
Hixie's avatar
Hixie committed
254
      defaultVerticalAlignment: defaultVerticalAlignment,
255
      textBaseline: textBaseline,
Hixie's avatar
Hixie committed
256 257 258 259 260
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderTable renderObject) {
261
    assert(debugCheckHasDirectionality(context));
262
    assert(renderObject.columns == (children.isNotEmpty ? children[0].children!.length : 0));
Hixie's avatar
Hixie committed
263 264 265 266
    assert(renderObject.rows == children.length);
    renderObject
      ..columnWidths = columnWidths
      ..defaultColumnWidth = defaultColumnWidth
267
      ..textDirection = textDirection ?? Directionality.of(context)!
Hixie's avatar
Hixie committed
268
      ..border = border
269
      ..rowDecorations = _rowDecorations
270
      ..configuration = createLocalImageConfiguration(context)
Hixie's avatar
Hixie committed
271 272 273 274 275 276 277 278 279
      ..defaultVerticalAlignment = defaultVerticalAlignment
      ..textBaseline = textBaseline;
  }
}

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

  @override
280
  Table get widget => super.widget as Table;
Hixie's avatar
Hixie committed
281 282

  @override
283
  RenderTable get renderObject => super.renderObject as RenderTable;
Hixie's avatar
Hixie committed
284 285 286 287 288 289 290

  // 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
291
  void mount(Element? parent, dynamic newSlot) {
Hixie's avatar
Hixie committed
292
    super.mount(parent, newSlot);
293
    _children = widget.children.map<_TableElementRow>((TableRow row) {
294
      return _TableElementRow(
Hixie's avatar
Hixie committed
295
        key: row.key,
296
        children: row.children!.map<Element>((Widget child) {
297 298
          assert(child != null);
          return inflateWidget(child, null);
299
        }).toList(growable: false),
Hixie's avatar
Hixie committed
300 301 302 303 304 305
      );
    }).toList(growable: false);
    _updateRenderObjectChildren();
  }

  @override
306
  void insertRenderObjectChild(RenderObject child, IndexedSlot<Element>? slot) {
Hixie's avatar
Hixie committed
307 308 309 310
    renderObject.setupParentData(child);
  }

  @override
311
  void moveRenderObjectChild(RenderObject child, IndexedSlot<Element>? oldSlot, IndexedSlot<Element>? newSlot) {
Hixie's avatar
Hixie committed
312 313 314
  }

  @override
315
  void removeRenderObjectChild(RenderObject child, IndexedSlot<Element>? slot) {
316
    final TableCellParentData childParentData = child.parentData! as TableCellParentData;
317
    renderObject.setChild(childParentData.x!, childParentData.y!, null);
Hixie's avatar
Hixie committed
318 319
  }

320
  final Set<Element> _forgottenChildren = HashSet<Element>();
Hixie's avatar
Hixie committed
321 322 323

  @override
  void update(Table newWidget) {
324
    final Map<LocalKey, List<Element>> oldKeyedRows = <LocalKey, List<Element>>{};
325
    for (final _TableElementRow row in _children) {
326
      if (row.key != null) {
327
        oldKeyedRows[row.key!] = row.children;
328 329
      }
    }
330 331
    final Iterator<_TableElementRow> oldUnkeyedRows = _children.where((_TableElementRow row) => row.key == null).iterator;
    final List<_TableElementRow> newChildren = <_TableElementRow>[];
332
    final Set<List<Element>> taken = <List<Element>>{};
333
    for (final TableRow row in newWidget.children) {
Hixie's avatar
Hixie committed
334 335
      List<Element> oldChildren;
      if (row.key != null && oldKeyedRows.containsKey(row.key)) {
336
        oldChildren = oldKeyedRows[row.key]!;
Hixie's avatar
Hixie committed
337 338 339 340 341 342
        taken.add(oldChildren);
      } else if (row.key == null && oldUnkeyedRows.moveNext()) {
        oldChildren = oldUnkeyedRows.current.children;
      } else {
        oldChildren = const <Element>[];
      }
343
      newChildren.add(_TableElementRow(
Hixie's avatar
Hixie committed
344
        key: row.key,
345
        children: updateChildren(oldChildren, row.children!, forgottenChildren: _forgottenChildren),
Hixie's avatar
Hixie committed
346 347 348
      ));
    }
    while (oldUnkeyedRows.moveNext())
349
      updateChildren(oldUnkeyedRows.current.children, const <Widget>[], forgottenChildren: _forgottenChildren);
350
    for (final List<Element> oldChildren in oldKeyedRows.values.where((List<Element> list) => !taken.contains(list)))
351
      updateChildren(oldChildren, const <Widget>[], forgottenChildren: _forgottenChildren);
352

Hixie's avatar
Hixie committed
353 354
    _children = newChildren;
    _updateRenderObjectChildren();
355
    _forgottenChildren.clear();
Hixie's avatar
Hixie committed
356 357 358 359 360 361 362
    super.update(newWidget);
    assert(widget == newWidget);
  }

  void _updateRenderObjectChildren() {
    assert(renderObject != null);
    renderObject.setFlatChildren(
363
      _children.isNotEmpty ? _children[0].children.length : 0,
364 365
      _children.expand<RenderBox>((_TableElementRow row) {
        return row.children.map<RenderBox>((Element child) {
366
          final RenderBox box = child.renderObject! as RenderBox;
367 368
          return box;
        });
369
      }).toList(),
Hixie's avatar
Hixie committed
370 371 372 373 374
    );
  }

  @override
  void visitChildren(ElementVisitor visitor) {
375
    for (final Element child in _children.expand<Element>((_TableElementRow row) => row.children)) {
376
      if (!_forgottenChildren.contains(child))
Hixie's avatar
Hixie committed
377 378 379 380 381
        visitor(child);
    }
  }

  @override
382 383
  bool forgetChild(Element child) {
    _forgottenChildren.add(child);
384
    super.forgetChild(child);
Hixie's avatar
Hixie committed
385 386 387 388
    return true;
  }
}

389 390 391 392 393 394
/// 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).
395
class TableCell extends ParentDataWidget<TableCellParentData> {
396
  /// Creates a widget that controls how a child of a [Table] is aligned.
397
  const TableCell({
398
    Key? key,
399
    this.verticalAlignment,
400
    required Widget child,
401
  }) : super(key: key, child: child);
Hixie's avatar
Hixie committed
402

403
  /// How this cell is aligned vertically.
404
  final TableCellVerticalAlignment? verticalAlignment;
Hixie's avatar
Hixie committed
405 406 407

  @override
  void applyParentData(RenderObject renderObject) {
408
    final TableCellParentData parentData = renderObject.parentData! as TableCellParentData;
Hixie's avatar
Hixie committed
409 410
    if (parentData.verticalAlignment != verticalAlignment) {
      parentData.verticalAlignment = verticalAlignment;
411
      final AbstractNode? targetParent = renderObject.parent;
Hixie's avatar
Hixie committed
412 413 414 415 416
      if (targetParent is RenderObject)
        targetParent.markNeedsLayout();
    }
  }

417 418 419
  @override
  Type get debugTypicalAncestorWidgetClass => Table;

Hixie's avatar
Hixie committed
420
  @override
421 422
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
423
    properties.add(EnumProperty<TableCellVerticalAlignment>('verticalAlignment', verticalAlignment));
Hixie's avatar
Hixie committed
424 425
  }
}