paginated_data_table.dart 18.2 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/widgets.dart';
8
import 'package:flutter/rendering.dart';
9
import 'package:flutter/gestures.dart' show DragStartBehavior;
10

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

Adam Barth's avatar
Adam Barth committed
25 26 27
/// A material design data table that shows data using multiple pages.
///
/// A paginated data table shows [rowsPerPage] rows of data per page and
28
/// provides controls for showing other pages.
Adam Barth's avatar
Adam Barth committed
29 30 31 32 33 34 35
///
/// Data is read lazily from from a [DataTableSource]. The widget is presented
/// as a [Card].
///
/// See also:
///
///  * [DataTable], which is not paginated.
36
///  * <https://material.io/go/design-data-tables#data-tables-tables-within-cards>
37 38 39
class PaginatedDataTable extends StatefulWidget {
  /// Creates a widget describing a paginated [DataTable] on a [Card].
  ///
40 41 42
  /// The [header] should give the card's header, typically a [Text] widget. It
  /// must not be null.
  ///
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
  /// 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.
62
  ///
63 64
  /// The [rowsPerPage] and [availableRowsPerPage] must not be null (they
  /// both have defaults, though, so don't have to be specified).
65
  PaginatedDataTable({
66 67
    Key? key,
    required this.header,
68
    this.actions,
69
    required this.columns,
70
    this.sortColumnIndex,
71
    this.sortAscending = true,
72
    this.onSelectAll,
73
    this.dataRowHeight = kMinInteractiveDimension,
74
    this.headingRowHeight = 56.0,
75 76
    this.horizontalMargin = 24.0,
    this.columnSpacing = 56.0,
77
    this.showCheckboxColumn = true,
78
    this.initialFirstRowIndex = 0,
79
    this.onPageChanged,
80 81
    this.rowsPerPage = defaultRowsPerPage,
    this.availableRowsPerPage = const <int>[defaultRowsPerPage, defaultRowsPerPage * 2, defaultRowsPerPage * 5, defaultRowsPerPage * 10],
82
    this.onRowsPerPageChanged,
83
    this.dragStartBehavior = DragStartBehavior.start,
84
    required this.source,
85 86
  }) : assert(header != null),
       assert(columns != null),
87
       assert(dragStartBehavior != null),
88 89 90
       assert(columns.isNotEmpty),
       assert(sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length)),
       assert(sortAscending != null),
91 92
       assert(dataRowHeight != null),
       assert(headingRowHeight != null),
93 94
       assert(horizontalMargin != null),
       assert(columnSpacing != null),
95
       assert(showCheckboxColumn != null),
96 97 98 99 100 101
       assert(rowsPerPage != null),
       assert(rowsPerPage > 0),
       assert(() {
         if (onRowsPerPageChanged != null)
           assert(availableRowsPerPage != null && availableRowsPerPage.contains(rowsPerPage));
         return true;
102
       }()),
103 104
       assert(source != null),
       super(key: key);
105

106 107 108
  /// The table card's header.
  ///
  /// This is typically a [Text] widget, but can also be a [ButtonBar] with
109
  /// [TextButton]s. Suitable defaults are automatically provided for the font,
110 111 112 113 114 115 116 117 118 119 120 121
  /// button color, button padding, and so forth.
  ///
  /// If items in the table are selectable, then, when the selection is not
  /// empty, the header is replaced by a count of the selected items.
  final Widget header;

  /// Icon buttons to show at the top right of the table.
  ///
  /// 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).
122
  final List<Widget>? actions;
123

124 125 126 127 128 129
  /// The configuration and labels for the columns in the table.
  final List<DataColumn> columns;

  /// The current primary sort key's column.
  ///
  /// See [DataTable.sortColumnIndex].
130
  final int? sortColumnIndex;
131 132 133 134 135 136 137 138 139 140 141

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

144 145
  /// The height of each row (excluding the row that contains column headings).
  ///
146 147
  /// This value is optional and defaults to kMinInteractiveDimension if not
  /// specified.
148 149 150 151 152 153 154
  final double dataRowHeight;

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

155 156 157 158 159 160 161 162 163 164 165 166 167 168
  /// 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.
  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;

169 170 171
  /// {@macro flutter.material.dataTable.showCheckboxColumn}
  final bool showCheckboxColumn;

172
  /// The index of the first row to display when the widget is first created.
173
  final int? initialFirstRowIndex;
174 175

  /// Invoked when the user switches to another page.
176 177
  ///
  /// The value is the index of the first row on the currently displayed page.
178
  final ValueChanged<int>? onPageChanged;
179 180 181

  /// The number of rows to show on each page.
  ///
182 183
  /// See also:
  ///
184 185
  ///  * [onRowsPerPageChanged]
  ///  * [defaultRowsPerPage]
186 187
  final int rowsPerPage;

188 189 190 191 192 193 194 195 196 197 198 199 200
  /// 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;

201 202 203 204
  /// 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.
205
  final ValueChanged<int?>? onRowsPerPageChanged;
206 207 208 209 210 211 212 213

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

214 215 216
  /// {@macro flutter.widgets.scrollable.dragStartBehavior}
  final DragStartBehavior dragStartBehavior;

217
  @override
218
  PaginatedDataTableState createState() => PaginatedDataTableState();
219 220 221 222 223 224
}

/// Holds the state of a [PaginatedDataTable].
///
/// The table can be programmatically paged using the [pageTo] method.
class PaginatedDataTableState extends State<PaginatedDataTable> {
225 226 227 228 229
  late int _firstRowIndex;
  late int _rowCount;
  late bool _rowCountApproximate;
  int _selectedRowCount = 0;
  final Map<int, DataRow?> _rows = <int, DataRow?>{};
230 231 232 233

  @override
  void initState() {
    super.initState();
234
    _firstRowIndex = PageStorage.of(context)?.readState(context) as int? ?? widget.initialFirstRowIndex ?? 0;
235
    widget.source.addListener(_handleDataSourceChanged);
236 237 238 239
    _handleDataSourceChanged();
  }

  @override
240 241 242 243 244
  void didUpdateWidget(PaginatedDataTable oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.source != widget.source) {
      oldWidget.source.removeListener(_handleDataSourceChanged);
      widget.source.addListener(_handleDataSourceChanged);
245 246 247 248 249 250
      _handleDataSourceChanged();
    }
  }

  @override
  void dispose() {
251
    widget.source.removeListener(_handleDataSourceChanged);
252 253 254 255 256
    super.dispose();
  }

  void _handleDataSourceChanged() {
    setState(() {
257 258 259
      _rowCount = widget.source.rowCount;
      _rowCountApproximate = widget.source.isRowCountApproximate;
      _selectedRowCount = widget.source.selectedRowCount;
260 261 262 263 264
      _rows.clear();
    });
  }

  /// Ensures that the given row is visible.
265 266
  void pageTo(int rowIndex) {
    final int oldFirstRowIndex = _firstRowIndex;
267
    setState(() {
268
      final int rowsPerPage = widget.rowsPerPage;
269 270
      _firstRowIndex = (rowIndex ~/ rowsPerPage) * rowsPerPage;
    });
271
    if ((widget.onPageChanged != null) &&
272
        (oldFirstRowIndex != _firstRowIndex))
273
      widget.onPageChanged!(_firstRowIndex);
274 275 276
  }

  DataRow _getBlankRowFor(int index) {
277
    return DataRow.byIndex(
278
      index: index,
279
      cells: widget.columns.map<DataCell>((DataColumn column) => DataCell.empty).toList(),
280 281 282 283 284
    );
  }

  DataRow _getProgressIndicatorRowFor(int index) {
    bool haveProgressIndicator = false;
285
    final List<DataCell> cells = widget.columns.map<DataCell>((DataColumn column) {
286 287
      if (!column.numeric) {
        haveProgressIndicator = true;
288
        return const DataCell(CircularProgressIndicator());
289 290 291 292 293
      }
      return DataCell.empty;
    }).toList();
    if (!haveProgressIndicator) {
      haveProgressIndicator = true;
294
      cells[0] = const DataCell(CircularProgressIndicator());
295
    }
296
    return DataRow.byIndex(
297
      index: index,
298
      cells: cells,
299 300 301 302 303 304 305 306
    );
  }

  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) {
307
      DataRow? row;
308
      if (index < _rowCount || _rowCountApproximate) {
309
        row = _rows.putIfAbsent(index, () => widget.source.getRow(index));
310 311 312 313 314 315 316 317 318 319 320
        if (row == null && !haveProgressIndicator) {
          row ??= _getProgressIndicatorRowFor(index);
          haveProgressIndicator = true;
        }
      }
      row ??= _getBlankRowFor(index);
      result.add(row);
    }
    return result;
  }

321 322 323 324 325 326 327 328
  void _handlePrevious() {
    pageTo(math.max(_firstRowIndex - widget.rowsPerPage, 0));
  }

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

329
  final GlobalKey _tableKey = GlobalKey();
330 331 332

  @override
  Widget build(BuildContext context) {
333
    // TODO(ianh): This whole build function doesn't handle RTL yet.
334
    assert(debugCheckHasMaterialLocalizations(context));
335
    final ThemeData themeData = Theme.of(context)!;
336
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
337 338
    // HEADER
    final List<Widget> headerWidgets = <Widget>[];
339
    double startPadding = 24.0;
340
    if (_selectedRowCount == 0) {
341
      headerWidgets.add(Expanded(child: widget.header));
342
      if (widget.header is ButtonBar) {
343 344 345 346 347
        // We adjust the padding when a button bar is present, because the
        // ButtonBar introduces 2 pixels of outside padding, plus 2 pixels
        // around each button on each side, and the button itself will have 8
        // pixels internally on each side, yet we want the left edge of the
        // inside of the button to line up with the 24.0 left inset.
348
        startPadding = 12.0;
349 350
      }
    } else {
351 352
      headerWidgets.add(Expanded(
        child: Text(localizations.selectedRowCountTitle(_selectedRowCount)),
353
      ));
354
    }
355
    if (widget.actions != null) {
356
      headerWidgets.addAll(
357
        widget.actions!.map<Widget>((Widget action) {
358
          return Padding(
359
            // 8.0 is the default padding of an icon button
360
            padding: const EdgeInsetsDirectional.only(start: 24.0 - 8.0 * 2.0),
361
            child: action,
362 363 364 365 366 367
          );
        }).toList()
      );
    }

    // FOOTER
368
    final TextStyle? footerTextStyle = themeData.textTheme.caption;
369
    final List<Widget> footerWidgets = <Widget>[];
370 371
    if (widget.onRowsPerPageChanged != null) {
      final List<Widget> availableRowsPerPage = widget.availableRowsPerPage
372
        .where((int value) => value <= _rowCount || value == widget.rowsPerPage)
373
        .map<DropdownMenuItem<int>>((int value) {
374
          return DropdownMenuItem<int>(
375
            value: value,
376
            child: Text('$value'),
377 378 379 380
          );
        })
        .toList();
      footerWidgets.addAll(<Widget>[
381 382 383
        Container(width: 14.0), // to match trailing padding in case we overflow and end up scrolling
        Text(localizations.rowsPerPageTitle),
        ConstrainedBox(
384
          constraints: const BoxConstraints(minWidth: 64.0), // 40.0 for the text, 24.0 for the icon
385
          child: Align(
386
            alignment: AlignmentDirectional.centerEnd,
387 388
            child: DropdownButtonHideUnderline(
              child: DropdownButton<int>(
389
                items: availableRowsPerPage.cast<DropdownMenuItem<int>>(),
390 391 392 393 394 395 396
                value: widget.rowsPerPage,
                onChanged: widget.onRowsPerPageChanged,
                style: footerTextStyle,
                iconSize: 24.0,
              ),
            ),
          ),
397 398 399 400
        ),
      ]);
    }
    footerWidgets.addAll(<Widget>[
401 402
      Container(width: 32.0),
      Text(
403 404 405 406
        localizations.pageRowsInfoTitle(
          _firstRowIndex + 1,
          _firstRowIndex + widget.rowsPerPage,
          _rowCount,
407
          _rowCountApproximate,
408
        ),
409
      ),
410 411
      Container(width: 32.0),
      IconButton(
412
        icon: const Icon(Icons.chevron_left),
413
        padding: EdgeInsets.zero,
414
        tooltip: localizations.previousPageTooltip,
415
        onPressed: _firstRowIndex <= 0 ? null : _handlePrevious,
416
      ),
417 418
      Container(width: 24.0),
      IconButton(
419
        icon: const Icon(Icons.chevron_right),
420
        padding: EdgeInsets.zero,
421
        tooltip: localizations.nextPageTooltip,
422
        onPressed: (!_rowCountApproximate && (_firstRowIndex + widget.rowsPerPage >= _rowCount)) ? null : _handleNext,
423
      ),
424
      Container(width: 14.0),
425
    ]);
426 427

    // CARD
428 429 430 431 432 433 434 435 436 437 438 439 440
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return Card(
          semanticContainer: false,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              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
441 442
                  style: _selectedRowCount > 0 ? themeData.textTheme.subtitle1!.copyWith(color: themeData.accentColor)
                                               : themeData.textTheme.headline6!.copyWith(fontWeight: FontWeight.w400),
443 444 445 446 447 448 449 450 451 452 453 454 455 456
                  child: IconTheme.merge(
                    data: const IconThemeData(
                      opacity: 0.54
                    ),
                    child: Ink(
                      height: 64.0,
                      color: _selectedRowCount > 0 ? themeData.secondaryHeaderColor : null,
                      child: Padding(
                        padding: EdgeInsetsDirectional.only(start: startPadding, end: 14.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: headerWidgets,
                        ),
                      ),
457 458 459 460
                    ),
                  ),
                ),
              ),
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                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,
                    dataRowHeight: widget.dataRowHeight,
                    headingRowHeight: widget.headingRowHeight,
                    horizontalMargin: widget.horizontalMargin,
                    columnSpacing: widget.columnSpacing,
476
                    showCheckboxColumn: widget.showCheckboxColumn,
477
                    showBottomBorder: true,
478 479 480
                    rows: _getRows(_firstRowIndex, widget.rowsPerPage),
                  ),
                ),
481
              ),
482
              DefaultTextStyle(
483
                style: footerTextStyle!,
484 485 486 487 488
                child: IconTheme.merge(
                  data: const IconThemeData(
                    opacity: 0.54
                  ),
                  child: Container(
489 490
                    // TODO(bkonyi): this won't handle text zoom correctly,
                    //  https://github.com/flutter/flutter/issues/48522
491 492 493 494 495 496 497 498 499
                    height: 56.0,
                    child: SingleChildScrollView(
                      dragStartBehavior: widget.dragStartBehavior,
                      scrollDirection: Axis.horizontal,
                      reverse: true,
                      child: Row(
                        children: footerWidgets,
                      ),
                    ),
500 501 502
                  ),
                ),
              ),
503
            ],
504
          ),
505 506
        );
      },
507 508 509
    );
  }
}