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 106 107 108
       assert(rowsPerPage != null),
       assert(rowsPerPage > 0),
       assert(() {
         if (onRowsPerPageChanged != null)
           assert(availableRowsPerPage != null && availableRowsPerPage.contains(rowsPerPage));
         return true;
109
       }()),
110 111 112 113 114
       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.',
       );
115

116
  /// The table card's optional header.
117
  ///
118 119 120
  /// 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.
121 122
  ///
  /// If items in the table are selectable, then, when the selection is not
123 124 125
  /// empty, the header is replaced by a count of the selected items. The
  /// [actions] are still visible when items are selected.
  final Widget? header;
126

127 128
  /// Icon buttons to show at the top end side of the table. The [header] must
  /// not be null to show the actions.
129 130 131 132 133
  ///
  /// 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).
134
  final List<Widget>? actions;
135

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

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

  /// 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].
154
  final ValueSetter<bool?>? onSelectAll;
155

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

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

167 168 169 170 171 172 173
  /// 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.
174 175 176 177
  ///
  /// 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.
178 179 180 181 182 183 184
  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;

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

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

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

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

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

207 208 209 210 211 212 213 214 215 216 217 218 219
  /// 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;

220 221 222 223
  /// 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.
224
  final ValueChanged<int?>? onRowsPerPageChanged;
225 226 227 228 229 230 231 232

  /// 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;

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

236 237 238 239 240 241 242
  /// 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;

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

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

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

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

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

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

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

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

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

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

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

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

  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) {
342
      DataRow? row;
343
      if (index < _rowCount || _rowCountApproximate) {
344
        row = _rows.putIfAbsent(index, () => widget.source.getRow(index));
345 346 347 348 349 350 351 352 353 354 355
        if (row == null && !haveProgressIndicator) {
          row ??= _getProgressIndicatorRowFor(index);
          haveProgressIndicator = true;
        }
      }
      row ??= _getBlankRowFor(index);
      result.add(row);
    }
    return result;
  }

356 357 358 359
  void _handleFirst() {
    pageTo(0);
  }

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

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

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

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

375
  final GlobalKey _tableKey = GlobalKey();
376 377 378

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

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

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