paginated_data_table.dart 20.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
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
import 'dart:math' as math;

7
import 'package:flutter/gestures.dart' show DragStartBehavior;
8
import 'package:flutter/widgets.dart';
9 10

import 'card.dart';
11
import 'constants.dart';
12 13
import 'data_table.dart';
import 'data_table_source.dart';
14
import 'debug.dart';
15
import 'dropdown.dart';
16 17
import 'icon_button.dart';
import 'icons.dart';
18
import 'ink_decoration.dart';
19
import 'material_localizations.dart';
20
import 'progress_indicator.dart';
21
import 'theme.dart';
22

23
/// A Material Design data table that shows data using multiple pages.
Adam Barth's avatar
Adam Barth committed
24 25
///
/// A paginated data table shows [rowsPerPage] rows of data per page and
26
/// provides controls for showing other pages.
Adam Barth's avatar
Adam Barth committed
27
///
nt4f04uNd's avatar
nt4f04uNd committed
28
/// Data is read lazily from a [DataTableSource]. The widget is presented
Adam Barth's avatar
Adam Barth committed
29 30 31 32 33
/// as a [Card].
///
/// See also:
///
///  * [DataTable], which is not paginated.
34
///  * <https://material.io/go/design-data-tables#data-tables-tables-within-cards>
35 36 37
class PaginatedDataTable extends StatefulWidget {
  /// Creates a widget describing a paginated [DataTable] on a [Card].
  ///
38
  /// The [header] should give the card's header, typically a [Text] widget.
39
  ///
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
  /// The [columns] argument must be a list of as many [DataColumn] objects as
  /// the table is to have columns, ignoring the leading checkbox column if any.
  /// The [columns] argument must have a length greater than zero and cannot be
  /// null.
  ///
  /// If the table is sorted, the column that provides the current primary key
  /// should be specified by index in [sortColumnIndex], 0 meaning the first
  /// column in [columns], 1 being the next one, and so forth.
  ///
  /// The actual sort order can be specified using [sortAscending]; if the sort
  /// order is ascending, this should be true (the default), otherwise it should
  /// be false.
  ///
  /// The [source] must not be null. The [source] should be a long-lived
  /// [DataTableSource]. The same source should be provided each time a
  /// particular [PaginatedDataTable] widget is created; avoid creating a new
  /// [DataTableSource] with each new instance of the [PaginatedDataTable]
  /// widget unless the data table really is to now show entirely different
  /// data from a new source.
59
  ///
60 61
  /// The [rowsPerPage] and [availableRowsPerPage] must not be null (they
  /// both have defaults, though, so don't have to be specified).
62 63 64 65
  ///
  /// Themed by [DataTableTheme]. [DataTableThemeData.decoration] is ignored.
  /// To modify the border or background color of the [PaginatedDataTable], use
  /// [CardTheme], since a [Card] wraps the inner [DataTable].
66
  PaginatedDataTable({
67
    super.key,
68
    this.header,
69
    this.actions,
70
    required this.columns,
71
    this.sortColumnIndex,
72
    this.sortAscending = true,
73
    this.onSelectAll,
74
    this.dataRowHeight = kMinInteractiveDimension,
75
    this.headingRowHeight = 56.0,
76 77
    this.horizontalMargin = 24.0,
    this.columnSpacing = 56.0,
78
    this.showCheckboxColumn = true,
79
    this.showFirstLastButtons = false,
80
    this.initialFirstRowIndex = 0,
81
    this.onPageChanged,
82 83
    this.rowsPerPage = defaultRowsPerPage,
    this.availableRowsPerPage = const <int>[defaultRowsPerPage, defaultRowsPerPage * 2, defaultRowsPerPage * 5, defaultRowsPerPage * 10],
84
    this.onRowsPerPageChanged,
85
    this.dragStartBehavior = DragStartBehavior.start,
86
    this.arrowHeadColor,
87
    required this.source,
88
    this.checkboxHorizontalMargin,
89 90
    this.controller,
    this.primary,
91
  }) : assert(actions == null || (actions != null && header != null)),
92
       assert(columns != null),
93
       assert(dragStartBehavior != null),
94 95 96
       assert(columns.isNotEmpty),
       assert(sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length)),
       assert(sortAscending != null),
97 98
       assert(dataRowHeight != null),
       assert(headingRowHeight != null),
99 100
       assert(horizontalMargin != null),
       assert(columnSpacing != null),
101
       assert(showCheckboxColumn != null),
102
       assert(showFirstLastButtons != null),
103 104 105
       assert(rowsPerPage != null),
       assert(rowsPerPage > 0),
       assert(() {
106
         if (onRowsPerPageChanged != null) {
107
           assert(availableRowsPerPage != null && availableRowsPerPage.contains(rowsPerPage));
108
         }
109
         return true;
110
       }()),
111 112 113 114 115
       assert(source != null),
       assert(!(controller != null && (primary ?? false)),
          'Primary ScrollViews obtain their ScrollController via inheritance from a PrimaryScrollController widget. '
          'You cannot both set primary to true and pass an explicit controller.',
       );
116

117
  /// The table card's optional header.
118
  ///
119 120 121
  /// This is typically a [Text] widget, but can also be a [Row] of
  /// [TextButton]s. To show icon buttons at the top end side of the table with
  /// a header, set the [actions] property.
122 123
  ///
  /// If items in the table are selectable, then, when the selection is not
124 125 126
  /// empty, the header is replaced by a count of the selected items. The
  /// [actions] are still visible when items are selected.
  final Widget? header;
127

128 129
  /// Icon buttons to show at the top end side of the table. The [header] must
  /// not be null to show the actions.
130 131 132 133 134
  ///
  /// Typically, the exact actions included in this list will vary based on
  /// whether any rows are selected or not.
  ///
  /// These should be size 24.0 with default padding (8.0).
135
  final List<Widget>? actions;
136

137 138 139 140 141 142
  /// The configuration and labels for the columns in the table.
  final List<DataColumn> columns;

  /// The current primary sort key's column.
  ///
  /// See [DataTable.sortColumnIndex].
143
  final int? sortColumnIndex;
144 145 146 147 148 149 150 151 152 153 154

  /// Whether the column mentioned in [sortColumnIndex], if any, is sorted
  /// in ascending order.
  ///
  /// See [DataTable.sortAscending].
  final bool sortAscending;

  /// Invoked when the user selects or unselects every row, using the
  /// checkbox in the heading row.
  ///
  /// See [DataTable.onSelectAll].
155
  final ValueSetter<bool?>? onSelectAll;
156

157 158
  /// The height of each row (excluding the row that contains column headings).
  ///
159 160
  /// This value is optional and defaults to kMinInteractiveDimension if not
  /// specified.
161 162 163 164 165 166 167
  final double dataRowHeight;

  /// The height of the heading row.
  ///
  /// This value is optional and defaults to 56.0 if not specified.
  final double headingRowHeight;

168 169 170 171 172 173 174
  /// The horizontal margin between the edges of the table and the content
  /// in the first and last cells of each row.
  ///
  /// When a checkbox is displayed, it is also the margin between the checkbox
  /// the content in the first data column.
  ///
  /// This value defaults to 24.0 to adhere to the Material Design specifications.
175 176 177 178
  ///
  /// If [checkboxHorizontalMargin] is null, then [horizontalMargin] is also the
  /// margin between the edge of the table and the checkbox, as well as the
  /// margin between the checkbox and the content in the first data column.
179 180 181 182 183 184 185
  final double horizontalMargin;

  /// The horizontal margin between the contents of each data column.
  ///
  /// This value defaults to 56.0 to adhere to the Material Design specifications.
  final double columnSpacing;

186 187 188
  /// {@macro flutter.material.dataTable.showCheckboxColumn}
  final bool showCheckboxColumn;

189 190 191
  /// Flag to display the pagination buttons to go to the first and last pages.
  final bool showFirstLastButtons;

192
  /// The index of the first row to display when the widget is first created.
193
  final int? initialFirstRowIndex;
194 195

  /// Invoked when the user switches to another page.
196 197
  ///
  /// The value is the index of the first row on the currently displayed page.
198
  final ValueChanged<int>? onPageChanged;
199 200 201

  /// The number of rows to show on each page.
  ///
202 203
  /// See also:
  ///
204 205
  ///  * [onRowsPerPageChanged]
  ///  * [defaultRowsPerPage]
206 207
  final int rowsPerPage;

208 209 210 211 212 213 214 215 216 217 218 219 220
  /// The default value for [rowsPerPage].
  ///
  /// Useful when initializing the field that will hold the current
  /// [rowsPerPage], when implemented [onRowsPerPageChanged].
  static const int defaultRowsPerPage = 10;

  /// The options to offer for the rowsPerPage.
  ///
  /// The current [rowsPerPage] must be a value in this list.
  ///
  /// The values in this list should be sorted in ascending order.
  final List<int> availableRowsPerPage;

221 222 223 224
  /// Invoked when the user selects a different number of rows per page.
  ///
  /// If this is null, then the value given by [rowsPerPage] will be used
  /// and no affordance will be provided to change the value.
225
  final ValueChanged<int?>? onRowsPerPageChanged;
226 227 228 229 230 231 232 233

  /// The data source which provides data to show in each row. Must be non-null.
  ///
  /// This object should generally have a lifetime longer than the
  /// [PaginatedDataTable] widget itself; it should be reused each time the
  /// [PaginatedDataTable] constructor is called.
  final DataTableSource source;

234 235 236
  /// {@macro flutter.widgets.scrollable.dragStartBehavior}
  final DragStartBehavior dragStartBehavior;

237 238 239 240 241 242 243
  /// Horizontal margin around the checkbox, if it is displayed.
  ///
  /// If null, then [horizontalMargin] is used as the margin between the edge
  /// of the table and the checkbox, as well as the margin between the checkbox
  /// and the content in the first data column. This value defaults to 24.0.
  final double? checkboxHorizontalMargin;

244 245 246
  /// Defines the color of the arrow heads in the footer.
  final Color? arrowHeadColor;

247 248 249 250 251 252
  /// {@macro flutter.widgets.scroll_view.controller}
  final ScrollController? controller;

  /// {@macro flutter.widgets.scroll_view.primary}
  final bool? primary;

253
  @override
254
  PaginatedDataTableState createState() => PaginatedDataTableState();
255 256 257 258 259 260
}

/// Holds the state of a [PaginatedDataTable].
///
/// The table can be programmatically paged using the [pageTo] method.
class PaginatedDataTableState extends State<PaginatedDataTable> {
261 262 263 264 265
  late int _firstRowIndex;
  late int _rowCount;
  late bool _rowCountApproximate;
  int _selectedRowCount = 0;
  final Map<int, DataRow?> _rows = <int, DataRow?>{};
266 267 268 269

  @override
  void initState() {
    super.initState();
270
    _firstRowIndex = PageStorage.of(context)?.readState(context) as int? ?? widget.initialFirstRowIndex ?? 0;
271
    widget.source.addListener(_handleDataSourceChanged);
272 273 274 275
    _handleDataSourceChanged();
  }

  @override
276 277 278 279 280
  void didUpdateWidget(PaginatedDataTable oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.source != widget.source) {
      oldWidget.source.removeListener(_handleDataSourceChanged);
      widget.source.addListener(_handleDataSourceChanged);
281 282 283 284 285 286
      _handleDataSourceChanged();
    }
  }

  @override
  void dispose() {
287
    widget.source.removeListener(_handleDataSourceChanged);
288 289 290 291 292
    super.dispose();
  }

  void _handleDataSourceChanged() {
    setState(() {
293 294 295
      _rowCount = widget.source.rowCount;
      _rowCountApproximate = widget.source.isRowCountApproximate;
      _selectedRowCount = widget.source.selectedRowCount;
296 297 298 299 300
      _rows.clear();
    });
  }

  /// Ensures that the given row is visible.
301 302
  void pageTo(int rowIndex) {
    final int oldFirstRowIndex = _firstRowIndex;
303
    setState(() {
304
      final int rowsPerPage = widget.rowsPerPage;
305 306
      _firstRowIndex = (rowIndex ~/ rowsPerPage) * rowsPerPage;
    });
307
    if ((widget.onPageChanged != null) &&
308
        (oldFirstRowIndex != _firstRowIndex)) {
309
      widget.onPageChanged!(_firstRowIndex);
310
    }
311 312 313
  }

  DataRow _getBlankRowFor(int index) {
314
    return DataRow.byIndex(
315
      index: index,
316
      cells: widget.columns.map<DataCell>((DataColumn column) => DataCell.empty).toList(),
317 318 319 320 321
    );
  }

  DataRow _getProgressIndicatorRowFor(int index) {
    bool haveProgressIndicator = false;
322
    final List<DataCell> cells = widget.columns.map<DataCell>((DataColumn column) {
323 324
      if (!column.numeric) {
        haveProgressIndicator = true;
325
        return const DataCell(CircularProgressIndicator());
326 327 328 329 330
      }
      return DataCell.empty;
    }).toList();
    if (!haveProgressIndicator) {
      haveProgressIndicator = true;
331
      cells[0] = const DataCell(CircularProgressIndicator());
332
    }
333
    return DataRow.byIndex(
334
      index: index,
335
      cells: cells,
336 337 338 339 340 341 342 343
    );
  }

  List<DataRow> _getRows(int firstRowIndex, int rowsPerPage) {
    final List<DataRow> result = <DataRow>[];
    final int nextPageFirstRowIndex = firstRowIndex + rowsPerPage;
    bool haveProgressIndicator = false;
    for (int index = firstRowIndex; index < nextPageFirstRowIndex; index += 1) {
344
      DataRow? row;
345
      if (index < _rowCount || _rowCountApproximate) {
346
        row = _rows.putIfAbsent(index, () => widget.source.getRow(index));
347 348 349 350 351 352 353 354 355 356 357
        if (row == null && !haveProgressIndicator) {
          row ??= _getProgressIndicatorRowFor(index);
          haveProgressIndicator = true;
        }
      }
      row ??= _getBlankRowFor(index);
      result.add(row);
    }
    return result;
  }

358 359 360 361
  void _handleFirst() {
    pageTo(0);
  }

362 363 364 365 366 367 368 369
  void _handlePrevious() {
    pageTo(math.max(_firstRowIndex - widget.rowsPerPage, 0));
  }

  void _handleNext() {
    pageTo(_firstRowIndex + widget.rowsPerPage);
  }

370 371 372 373 374 375 376
  void _handleLast() {
    pageTo(((_rowCount - 1) / widget.rowsPerPage).floor() * widget.rowsPerPage);
  }

  bool _isNextPageUnavailable() => !_rowCountApproximate &&
      (_firstRowIndex + widget.rowsPerPage >= _rowCount);

377
  final GlobalKey _tableKey = GlobalKey();
378 379 380

  @override
  Widget build(BuildContext context) {
381
    // TODO(ianh): This whole build function doesn't handle RTL yet.
382
    assert(debugCheckHasMaterialLocalizations(context));
383
    final ThemeData themeData = Theme.of(context);
384
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
385 386
    // HEADER
    final List<Widget> headerWidgets = <Widget>[];
387 388 389
    if (_selectedRowCount == 0 && widget.header != null) {
      headerWidgets.add(Expanded(child: widget.header!));
    } else if (widget.header != null) {
390 391
      headerWidgets.add(Expanded(
        child: Text(localizations.selectedRowCountTitle(_selectedRowCount)),
392
      ));
393
    }
394
    if (widget.actions != null) {
395
      headerWidgets.addAll(
396
        widget.actions!.map<Widget>((Widget action) {
397
          return Padding(
398
            // 8.0 is the default padding of an icon button
399
            padding: const EdgeInsetsDirectional.only(start: 24.0 - 8.0 * 2.0),
400
            child: action,
401
          );
402
        }).toList(),
403 404 405 406
      );
    }

    // FOOTER
407
    final TextStyle? footerTextStyle = themeData.textTheme.caption;
408
    final List<Widget> footerWidgets = <Widget>[];
409 410
    if (widget.onRowsPerPageChanged != null) {
      final List<Widget> availableRowsPerPage = widget.availableRowsPerPage
411
        .where((int value) => value <= _rowCount || value == widget.rowsPerPage)
412
        .map<DropdownMenuItem<int>>((int value) {
413
          return DropdownMenuItem<int>(
414
            value: value,
415
            child: Text('$value'),
416 417 418 419
          );
        })
        .toList();
      footerWidgets.addAll(<Widget>[
420 421 422
        Container(width: 14.0), // to match trailing padding in case we overflow and end up scrolling
        Text(localizations.rowsPerPageTitle),
        ConstrainedBox(
423
          constraints: const BoxConstraints(minWidth: 64.0), // 40.0 for the text, 24.0 for the icon
424
          child: Align(
425
            alignment: AlignmentDirectional.centerEnd,
426 427
            child: DropdownButtonHideUnderline(
              child: DropdownButton<int>(
428
                items: availableRowsPerPage.cast<DropdownMenuItem<int>>(),
429 430 431 432 433 434
                value: widget.rowsPerPage,
                onChanged: widget.onRowsPerPageChanged,
                style: footerTextStyle,
              ),
            ),
          ),
435 436 437 438
        ),
      ]);
    }
    footerWidgets.addAll(<Widget>[
439 440
      Container(width: 32.0),
      Text(
441 442 443 444
        localizations.pageRowsInfoTitle(
          _firstRowIndex + 1,
          _firstRowIndex + widget.rowsPerPage,
          _rowCount,
445
          _rowCountApproximate,
446
        ),
447
      ),
448
      Container(width: 32.0),
449 450
      if (widget.showFirstLastButtons)
        IconButton(
451
          icon: Icon(Icons.skip_previous, color: widget.arrowHeadColor),
452 453 454 455
          padding: EdgeInsets.zero,
          tooltip: localizations.firstPageTooltip,
          onPressed: _firstRowIndex <= 0 ? null : _handleFirst,
        ),
456
      IconButton(
457
        icon: Icon(Icons.chevron_left, color: widget.arrowHeadColor),
458
        padding: EdgeInsets.zero,
459
        tooltip: localizations.previousPageTooltip,
460
        onPressed: _firstRowIndex <= 0 ? null : _handlePrevious,
461
      ),
462 463
      Container(width: 24.0),
      IconButton(
464
        icon: Icon(Icons.chevron_right, color: widget.arrowHeadColor),
465
        padding: EdgeInsets.zero,
466
        tooltip: localizations.nextPageTooltip,
467
        onPressed: _isNextPageUnavailable() ? null : _handleNext,
468
      ),
469 470
      if (widget.showFirstLastButtons)
        IconButton(
471
          icon: Icon(Icons.skip_next, color: widget.arrowHeadColor),
472 473 474 475 476 477
          padding: EdgeInsets.zero,
          tooltip: localizations.lastPageTooltip,
          onPressed: _isNextPageUnavailable()
              ? null
              : _handleLast,
        ),
478
      Container(width: 14.0),
479
    ]);
480 481

    // CARD
482 483 484 485 486
    return Card(
      semanticContainer: false,
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Column(
487 488
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
489 490 491 492 493 494 495
              if (headerWidgets.isNotEmpty)
                Semantics(
                  container: true,
                  child: DefaultTextStyle(
                    // These typographic styles aren't quite the regular ones. We pick the closest ones from the regular
                    // list and then tweak them appropriately.
                    // See https://material.io/design/components/data-tables.html#tables-within-cards
496
                    style: _selectedRowCount > 0 ? themeData.textTheme.subtitle1!.copyWith(color: themeData.colorScheme.secondary)
497 498 499
                                                 : themeData.textTheme.headline6!.copyWith(fontWeight: FontWeight.w400),
                    child: IconTheme.merge(
                      data: const IconThemeData(
500
                        opacity: 0.54,
501 502 503 504 505
                      ),
                      child: Ink(
                        height: 64.0,
                        color: _selectedRowCount > 0 ? themeData.secondaryHeaderColor : null,
                        child: Padding(
506
                          padding: const EdgeInsetsDirectional.only(start: 24, end: 14.0),
507 508 509 510
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: headerWidgets,
                          ),
511 512
                        ),
                      ),
513 514 515
                    ),
                  ),
                ),
516 517
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
518 519
                primary: widget.primary,
                controller: widget.controller,
520 521 522 523 524 525 526 527 528
                dragStartBehavior: widget.dragStartBehavior,
                child: ConstrainedBox(
                  constraints: BoxConstraints(minWidth: constraints.minWidth),
                  child: DataTable(
                    key: _tableKey,
                    columns: widget.columns,
                    sortColumnIndex: widget.sortColumnIndex,
                    sortAscending: widget.sortAscending,
                    onSelectAll: widget.onSelectAll,
529 530 531
                    // Make sure no decoration is set on the DataTable
                    // from the theme, as its already wrapped in a Card.
                    decoration: const BoxDecoration(),
532 533 534
                    dataRowHeight: widget.dataRowHeight,
                    headingRowHeight: widget.headingRowHeight,
                    horizontalMargin: widget.horizontalMargin,
535
                    checkboxHorizontalMargin: widget.checkboxHorizontalMargin,
536
                    columnSpacing: widget.columnSpacing,
537
                    showCheckboxColumn: widget.showCheckboxColumn,
538
                    showBottomBorder: true,
539 540 541
                    rows: _getRows(_firstRowIndex, widget.rowsPerPage),
                  ),
                ),
542
              ),
543
              DefaultTextStyle(
544
                style: footerTextStyle!,
545 546
                child: IconTheme.merge(
                  data: const IconThemeData(
547
                    opacity: 0.54,
548
                  ),
549
                  child: SizedBox(
550 551
                    // TODO(bkonyi): this won't handle text zoom correctly,
                    //  https://github.com/flutter/flutter/issues/48522
552 553 554 555 556 557 558 559 560
                    height: 56.0,
                    child: SingleChildScrollView(
                      dragStartBehavior: widget.dragStartBehavior,
                      scrollDirection: Axis.horizontal,
                      reverse: true,
                      child: Row(
                        children: footerWidgets,
                      ),
                    ),
561 562 563
                  ),
                ),
              ),
564
            ],
565 566 567
          );
        },
      ),
568 569 570
    );
  }
}