paginated_data_table.dart 15.2 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/foundation.dart';
8
import 'package:flutter/widgets.dart';
9
import 'package:flutter/rendering.dart';
10

11 12
import 'button.dart';
import 'button_bar.dart';
13 14 15
import 'card.dart';
import 'data_table.dart';
import 'data_table_source.dart';
16
import 'dropdown.dart';
Ian Hickson's avatar
Ian Hickson committed
17
import 'icon.dart';
18 19 20 21
import 'icon_button.dart';
import 'icon_theme.dart';
import 'icon_theme_data.dart';
import 'icons.dart';
22
import 'progress_indicator.dart';
23
import 'theme.dart';
24

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

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
  /// 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;

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  /// 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.
137 138
  ///
  /// The value is the index of the first row on the currently displayed page.
139 140 141 142
  final ValueChanged<int> onPageChanged;

  /// The number of rows to show on each page.
  ///
143 144 145 146
  /// See also:
  ///
  /// * [onRowsPerPageChanged]
  /// * [defaultRowsPerPage]
147 148
  final int rowsPerPage;

149 150 151 152 153 154 155 156 157 158 159 160 161
  /// 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;

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  /// 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;
186
  int _selectedRowCount;
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
  final Map<int, DataRow> _rows = <int, DataRow>{};

  @override
  void initState() {
    super.initState();
    _firstRowIndex = PageStorage.of(context)?.readState(context) ?? config.initialFirstRowIndex ?? 0;
    config.source.addListener(_handleDataSourceChanged);
    _handleDataSourceChanged();
  }

  @override
  void didUpdateConfig(PaginatedDataTable oldConfig) {
    super.didUpdateConfig(oldConfig);
    if (oldConfig.source != config.source) {
      oldConfig.source.removeListener(_handleDataSourceChanged);
      config.source.addListener(_handleDataSourceChanged);
      _handleDataSourceChanged();
    }
  }

  @override
  void dispose() {
    config.source.removeListener(_handleDataSourceChanged);
    super.dispose();
  }

  void _handleDataSourceChanged() {
    setState(() {
      _rowCount = config.source.rowCount;
      _rowCountApproximate = config.source.isRowCountApproximate;
217
      _selectedRowCount = config.source.selectedRowCount;
218 219 220 221 222
      _rows.clear();
    });
  }

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

  DataRow _getBlankRowFor(int index) {
    return new DataRow.byIndex(
      index: index,
237
      cells: config.columns.map<DataCell>((DataColumn column) => DataCell.empty).toList()
238 239 240 241 242
    );
  }

  DataRow _getProgressIndicatorRowFor(int index) {
    bool haveProgressIndicator = false;
243
    final List<DataCell> cells = config.columns.map<DataCell>((DataColumn column) {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
      if (!column.numeric) {
        haveProgressIndicator = true;
        return new DataCell(new CircularProgressIndicator());
      }
      return DataCell.empty;
    }).toList();
    if (!haveProgressIndicator) {
      haveProgressIndicator = true;
      cells[0] = new DataCell(new CircularProgressIndicator());
    }
    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) {
        row = _rows.putIfAbsent(index, () => config.source.getRow(index));
        if (row == null && !haveProgressIndicator) {
          row ??= _getProgressIndicatorRowFor(index);
          haveProgressIndicator = true;
        }
      }
      row ??= _getBlankRowFor(index);
      result.add(row);
    }
    return result;
  }

  final GlobalKey _tableKey = new GlobalKey();

  @override
  Widget build(BuildContext context) {
283
    // TODO(ianh): This whole build function doesn't handle RTL yet.
284
    final ThemeData themeData = Theme.of(context);
285 286 287 288
    // HEADER
    final List<Widget> headerWidgets = <Widget>[];
    double leftPadding = 24.0;
    if (_selectedRowCount == 0) {
289
      headerWidgets.add(new Expanded(child: config.header));
290 291 292 293 294 295 296 297 298 299 300
      if (config.header is ButtonBar) {
        // 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
        leftPadding = 12.0;
      }
    } else if (_selectedRowCount == 1) {
      // TODO(ianh): Real l10n.
301
      headerWidgets.add(new Expanded(child: new Text('1 item selected')));
302
    } else {
303
      headerWidgets.add(new Expanded(child: new Text('$_selectedRowCount items selected')));
304 305 306
    }
    if (config.actions != null) {
      headerWidgets.addAll(
307
        config.actions.map<Widget>((Widget widget) {
308 309
          return new Padding(
            // 8.0 is the default padding of an icon button
310
            padding: const EdgeInsets.only(left: 24.0 - 8.0 * 2.0),
311 312 313 314 315 316 317 318
            child: widget
          );
        }).toList()
      );
    }

    // FOOTER
    final TextStyle footerTextStyle = themeData.textTheme.caption;
319 320
    final List<Widget> footerWidgets = <Widget>[];
    if (config.onRowsPerPageChanged != null) {
321
      final List<Widget> availableRowsPerPage = config.availableRowsPerPage
322
        .where((int value) => value <= _rowCount)
323
        .map<DropdownMenuItem<int>>((int value) {
324
          return new DropdownMenuItem<int>(
325 326 327 328 329 330 331
            value: value,
            child: new Text('$value')
          );
        })
        .toList();
      footerWidgets.addAll(<Widget>[
        new Text('Rows per page:'),
332 333
        new DropdownButtonHideUnderline(
          child: new DropdownButton<int>(
334 335 336
            items: availableRowsPerPage,
            value: config.rowsPerPage,
            onChanged: config.onRowsPerPageChanged,
337
            style: footerTextStyle,
338 339 340 341 342 343 344 345 346 347 348 349
            iconSize: 24.0
          )
        ),
      ]);
    }
    footerWidgets.addAll(<Widget>[
      new Container(width: 32.0),
      new Text(
        '${_firstRowIndex + 1}\u2013${_firstRowIndex + config.rowsPerPage} ${ _rowCountApproximate ? "of about" : "of" } $_rowCount'
      ),
      new Container(width: 32.0),
      new IconButton(
Ian Hickson's avatar
Ian Hickson committed
350
        icon: new Icon(Icons.chevron_left),
351
        padding: EdgeInsets.zero,
352
        tooltip: 'Previous page',
353 354 355 356 357 358
        onPressed: _firstRowIndex <= 0 ? null : () {
          pageTo(math.max(_firstRowIndex - config.rowsPerPage, 0));
        }
      ),
      new Container(width: 24.0),
      new IconButton(
Ian Hickson's avatar
Ian Hickson committed
359
        icon: new Icon(Icons.chevron_right),
360
        padding: EdgeInsets.zero,
361
        tooltip: 'Next page',
362 363 364 365 366 367
        onPressed: (!_rowCountApproximate && (_firstRowIndex + config.rowsPerPage >= _rowCount)) ? null : () {
          pageTo(_firstRowIndex + config.rowsPerPage);
        }
      ),
      new Container(width: 14.0),
    ]);
368 369

    // CARD
370
    return new Card(
371 372
      child: new Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
373
        children: <Widget>[
374 375 376
          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.
377
            // See https://material.google.com/components/data-tables.html#data-tables-tables-within-cards
378 379
            style: _selectedRowCount > 0 ? themeData.textTheme.subhead.copyWith(color: themeData.accentColor)
                                         : themeData.textTheme.title.copyWith(fontWeight: FontWeight.w400),
Ian Hickson's avatar
Ian Hickson committed
380 381
            child: new IconTheme.merge(
              context: context,
382
              data: const IconThemeData(
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
                opacity: 0.54
              ),
              child: new ButtonTheme.bar(
                child: new Container(
                  height: 64.0,
                  padding: new EdgeInsets.fromLTRB(leftPadding, 0.0, 14.0, 0.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
                  decoration: _selectedRowCount > 0 ? new BoxDecoration(
                    backgroundColor: themeData.secondaryHeaderColor
                  ) : null,
                  child: new Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: headerWidgets
                  )
                )
              )
            )
          ),
403
          new SingleChildScrollView(
404 405 406 407 408 409 410 411 412 413 414
            scrollDirection: Axis.horizontal,
            child: new DataTable(
              key: _tableKey,
              columns: config.columns,
              sortColumnIndex: config.sortColumnIndex,
              sortAscending: config.sortAscending,
              onSelectAll: config.onSelectAll,
              rows: _getRows(_firstRowIndex, config.rowsPerPage)
            )
          ),
          new DefaultTextStyle(
415
            style: footerTextStyle,
Ian Hickson's avatar
Ian Hickson committed
416 417
            child: new IconTheme.merge(
              context: context,
418
              data: const IconThemeData(
419 420 421 422 423 424 425 426 427 428 429 430 431
                opacity: 0.54
              ),
              child: new Container(
                height: 56.0,
                child: new Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: footerWidgets
                )
              )
            )
          )
        ]
      )
432 433 434
    );
  }
}