paginated_data_table.dart 15.8 KB
Newer Older
1 2 3 4
// Copyright 2016 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.

5 6
import 'dart:math' as math;

7
import 'package:flutter/widgets.dart';
8
import 'package:flutter/rendering.dart';
9

10
import 'button_bar.dart';
11
import 'button_theme.dart';
12 13 14
import 'card.dart';
import 'data_table.dart';
import 'data_table_source.dart';
15
import 'dropdown.dart';
16 17
import 'icon_button.dart';
import 'icons.dart';
18
import 'material_localizations.dart';
19
import 'progress_indicator.dart';
20
import 'theme.dart';
21

Adam Barth's avatar
Adam Barth committed
22 23 24
/// A material design data table that shows data using multiple pages.
///
/// A paginated data table shows [rowsPerPage] rows of data per page and
25
/// provides controls for showing other pages.
Adam Barth's avatar
Adam Barth committed
26 27 28 29 30 31 32
///
/// Data is read lazily from from a [DataTableSource]. The widget is presented
/// as a [Card].
///
/// See also:
///
///  * [DataTable], which is not paginated.
33
///  * <https://material.io/go/design-data-tables#data-tables-tables-within-cards>
34 35 36
class PaginatedDataTable extends StatefulWidget {
  /// Creates a widget describing a paginated [DataTable] on a [Card].
  ///
37 38 39
  /// The [header] should give the card's header, typically a [Text] widget. It
  /// must not be null.
  ///
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
  PaginatedDataTable({
    Key key,
64 65
    @required this.header,
    this.actions,
66
    @required this.columns,
67
    this.sortColumnIndex,
68
    this.sortAscending = true,
69
    this.onSelectAll,
70
    this.initialFirstRowIndex = 0,
71
    this.onPageChanged,
72 73
    this.rowsPerPage = defaultRowsPerPage,
    this.availableRowsPerPage = const <int>[defaultRowsPerPage, defaultRowsPerPage * 2, defaultRowsPerPage * 5, defaultRowsPerPage * 10],
74
    this.onRowsPerPageChanged,
75
    @required this.source
76 77 78 79 80 81 82 83 84 85 86
  }) : assert(header != null),
       assert(columns != null),
       assert(columns.isNotEmpty),
       assert(sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length)),
       assert(sortAscending != null),
       assert(rowsPerPage != null),
       assert(rowsPerPage > 0),
       assert(() {
         if (onRowsPerPageChanged != null)
           assert(availableRowsPerPage != null && availableRowsPerPage.contains(rowsPerPage));
         return true;
87
       }()),
88 89
       assert(source != null),
       super(key: key);
90

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  /// The table card's header.
  ///
  /// This is typically a [Text] widget, but can also be a [ButtonBar] with
  /// [FlatButton]s. Suitable defaults are automatically provided for the font,
  /// 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).
  final List<Widget> actions;

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  /// The configuration and labels for the columns in the table.
  final List<DataColumn> columns;

  /// The current primary sort key's column.
  ///
  /// See [DataTable.sortColumnIndex].
  final int sortColumnIndex;

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

  /// The index of the first row to display when the widget is first created.
  final int initialFirstRowIndex;

  /// Invoked when the user switches to another page.
133 134
  ///
  /// The value is the index of the first row on the currently displayed page.
135 136 137 138
  final ValueChanged<int> onPageChanged;

  /// The number of rows to show on each page.
  ///
139 140 141 142
  /// See also:
  ///
  /// * [onRowsPerPageChanged]
  /// * [defaultRowsPerPage]
143 144
  final int rowsPerPage;

145 146 147 148 149 150 151 152 153 154 155 156 157
  /// 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;

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  /// 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.
  final ValueChanged<int> onRowsPerPageChanged;

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

  @override
  PaginatedDataTableState createState() => new PaginatedDataTableState();
}

/// Holds the state of a [PaginatedDataTable].
///
/// The table can be programmatically paged using the [pageTo] method.
class PaginatedDataTableState extends State<PaginatedDataTable> {
  int _firstRowIndex;
  int _rowCount;
  bool _rowCountApproximate;
182
  int _selectedRowCount;
183 184 185 186 187
  final Map<int, DataRow> _rows = <int, DataRow>{};

  @override
  void initState() {
    super.initState();
188 189
    _firstRowIndex = PageStorage.of(context)?.readState(context) ?? widget.initialFirstRowIndex ?? 0;
    widget.source.addListener(_handleDataSourceChanged);
190 191 192 193
    _handleDataSourceChanged();
  }

  @override
194 195 196 197 198
  void didUpdateWidget(PaginatedDataTable oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.source != widget.source) {
      oldWidget.source.removeListener(_handleDataSourceChanged);
      widget.source.addListener(_handleDataSourceChanged);
199 200 201 202 203 204
      _handleDataSourceChanged();
    }
  }

  @override
  void dispose() {
205
    widget.source.removeListener(_handleDataSourceChanged);
206 207 208 209 210
    super.dispose();
  }

  void _handleDataSourceChanged() {
    setState(() {
211 212 213
      _rowCount = widget.source.rowCount;
      _rowCountApproximate = widget.source.isRowCountApproximate;
      _selectedRowCount = widget.source.selectedRowCount;
214 215 216 217 218
      _rows.clear();
    });
  }

  /// Ensures that the given row is visible.
219 220
  void pageTo(int rowIndex) {
    final int oldFirstRowIndex = _firstRowIndex;
221
    setState(() {
222
      final int rowsPerPage = widget.rowsPerPage;
223 224
      _firstRowIndex = (rowIndex ~/ rowsPerPage) * rowsPerPage;
    });
225
    if ((widget.onPageChanged != null) &&
226
        (oldFirstRowIndex != _firstRowIndex))
227
      widget.onPageChanged(_firstRowIndex);
228 229 230 231 232
  }

  DataRow _getBlankRowFor(int index) {
    return new DataRow.byIndex(
      index: index,
233
      cells: widget.columns.map<DataCell>((DataColumn column) => DataCell.empty).toList()
234 235 236 237 238
    );
  }

  DataRow _getProgressIndicatorRowFor(int index) {
    bool haveProgressIndicator = false;
239
    final List<DataCell> cells = widget.columns.map<DataCell>((DataColumn column) {
240 241
      if (!column.numeric) {
        haveProgressIndicator = true;
242
        return const DataCell(CircularProgressIndicator());
243 244 245 246 247
      }
      return DataCell.empty;
    }).toList();
    if (!haveProgressIndicator) {
      haveProgressIndicator = true;
248
      cells[0] = const DataCell(CircularProgressIndicator());
249 250 251 252 253 254 255 256 257 258 259 260 261 262
    }
    return new DataRow.byIndex(
      index: index,
      cells: cells
    );
  }

  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) {
      DataRow row;
      if (index < _rowCount || _rowCountApproximate) {
263
        row = _rows.putIfAbsent(index, () => widget.source.getRow(index));
264 265 266 267 268 269 270 271 272 273 274
        if (row == null && !haveProgressIndicator) {
          row ??= _getProgressIndicatorRowFor(index);
          haveProgressIndicator = true;
        }
      }
      row ??= _getBlankRowFor(index);
      result.add(row);
    }
    return result;
  }

275 276 277 278 279 280 281 282
  void _handlePrevious() {
    pageTo(math.max(_firstRowIndex - widget.rowsPerPage, 0));
  }

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

283 284 285 286
  final GlobalKey _tableKey = new GlobalKey();

  @override
  Widget build(BuildContext context) {
287
    // TODO(ianh): This whole build function doesn't handle RTL yet.
288
    final ThemeData themeData = Theme.of(context);
289
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
290 291
    // HEADER
    final List<Widget> headerWidgets = <Widget>[];
292
    double startPadding = 24.0;
293
    if (_selectedRowCount == 0) {
294 295
      headerWidgets.add(new Expanded(child: widget.header));
      if (widget.header is ButtonBar) {
296 297 298 299 300 301
        // 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.
        // TODO(ianh): Better magic. See https://github.com/flutter/flutter/issues/4460
302
        startPadding = 12.0;
303 304
      }
    } else {
305 306 307
      headerWidgets.add(new Expanded(
        child: new Text(localizations.selectedRowCountTitle(_selectedRowCount)),
      ));
308
    }
309
    if (widget.actions != null) {
310
      headerWidgets.addAll(
311
        widget.actions.map<Widget>((Widget action) {
312 313
          return new Padding(
            // 8.0 is the default padding of an icon button
314
            padding: const EdgeInsetsDirectional.only(start: 24.0 - 8.0 * 2.0),
315
            child: action,
316 317 318 319 320 321 322
          );
        }).toList()
      );
    }

    // FOOTER
    final TextStyle footerTextStyle = themeData.textTheme.caption;
323
    final List<Widget> footerWidgets = <Widget>[];
324 325
    if (widget.onRowsPerPageChanged != null) {
      final List<Widget> availableRowsPerPage = widget.availableRowsPerPage
326
        .where((int value) => value <= _rowCount || value == widget.rowsPerPage)
327
        .map<DropdownMenuItem<int>>((int value) {
328
          return new DropdownMenuItem<int>(
329 330 331 332 333 334
            value: value,
            child: new Text('$value')
          );
        })
        .toList();
      footerWidgets.addAll(<Widget>[
335
        new Container(width: 14.0), // to match trailing padding in case we overflow and end up scrolling
336
        new Text(localizations.rowsPerPageTitle),
337 338 339 340 341 342 343 344 345 346 347 348 349 350
        new ConstrainedBox(
          constraints: const BoxConstraints(minWidth: 64.0), // 40.0 for the text, 24.0 for the icon
          child: new Align(
            alignment: AlignmentDirectional.centerEnd,
            child: new DropdownButtonHideUnderline(
              child: new DropdownButton<int>(
                items: availableRowsPerPage,
                value: widget.rowsPerPage,
                onChanged: widget.onRowsPerPageChanged,
                style: footerTextStyle,
                iconSize: 24.0,
              ),
            ),
          ),
351 352 353 354 355 356
        ),
      ]);
    }
    footerWidgets.addAll(<Widget>[
      new Container(width: 32.0),
      new Text(
357 358 359 360 361 362
        localizations.pageRowsInfoTitle(
          _firstRowIndex + 1,
          _firstRowIndex + widget.rowsPerPage,
          _rowCount,
          _rowCountApproximate
        )
363 364 365
      ),
      new Container(width: 32.0),
      new IconButton(
366
        icon: const Icon(Icons.chevron_left),
367
        padding: EdgeInsets.zero,
368
        tooltip: localizations.previousPageTooltip,
369
        onPressed: _firstRowIndex <= 0 ? null : _handlePrevious
370 371 372
      ),
      new Container(width: 24.0),
      new IconButton(
373
        icon: const Icon(Icons.chevron_right),
374
        padding: EdgeInsets.zero,
375
        tooltip: localizations.nextPageTooltip,
376
        onPressed: (!_rowCountApproximate && (_firstRowIndex + widget.rowsPerPage >= _rowCount)) ? null : _handleNext
377 378 379
      ),
      new Container(width: 14.0),
    ]);
380 381

    // CARD
382
    return new Card(
383
      semanticContainer: false,
384 385
      child: new Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
386
        children: <Widget>[
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
          new Semantics(
            container: true,
            child: new 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.google.com/components/data-tables.html#data-tables-tables-within-cards
              style: _selectedRowCount > 0 ? themeData.textTheme.subhead.copyWith(color: themeData.accentColor)
                                           : themeData.textTheme.title.copyWith(fontWeight: FontWeight.w400),
              child: IconTheme.merge(
                data: const IconThemeData(
                  opacity: 0.54
                ),
                child: new ButtonTheme.bar(
                  child: new Container(
                    height: 64.0,
                    padding: new EdgeInsetsDirectional.only(start: startPadding, end: 14.0),
                    // TODO(ianh): This decoration will prevent ink splashes from being visible.
                    // Instead, we should have a widget that prints the decoration on the material.
                    // See https://github.com/flutter/flutter/issues/3782
                    color: _selectedRowCount > 0 ? themeData.secondaryHeaderColor : null,
                    child: new Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: headerWidgets
                    )
411 412 413
                  )
                )
              )
414
            ),
415
          ),
416
          new SingleChildScrollView(
417 418 419
            scrollDirection: Axis.horizontal,
            child: new DataTable(
              key: _tableKey,
420 421 422 423 424
              columns: widget.columns,
              sortColumnIndex: widget.sortColumnIndex,
              sortAscending: widget.sortAscending,
              onSelectAll: widget.onSelectAll,
              rows: _getRows(_firstRowIndex, widget.rowsPerPage)
425 426 427
            )
          ),
          new DefaultTextStyle(
428
            style: footerTextStyle,
429
            child: IconTheme.merge(
430
              data: const IconThemeData(
431 432 433 434
                opacity: 0.54
              ),
              child: new Container(
                height: 56.0,
435 436 437 438 439 440 441 442 443 444 445 446
                child: new SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  reverse: true,
                  child: new Row(
                    children: footerWidgets,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
447 448 449
    );
  }
}