From 68f92d4f3407095641dcb4fcec95caa2a3a482e0 Mon Sep 17 00:00:00 2001 From: Ian Hickson Date: Tue, 7 Jun 2016 16:11:30 -0700 Subject: [PATCH] Provide UI to paginate PaginatedDataTable (#4382) Also: * Make PaginatedDataTable able to scroll itself horizontally. * Make drop down buttons support having an explicit text style and icon size given. * Fix a bug with drop-down buttons asserting when opened partly off-screen. * Make sure to pop the drop-down button's route if the drop-down button is discarded while the route is up. * Remove extraneous padding on drop-down buttons. (Couldn't figure out why it was there, and it breaks alignment when a drop-down is mixed with other text.) * Some docs improvements. * Add Route.isActive * Add a setState() method to ModalRoutes. --- .../lib/demo/data_table_demo.dart | 109 ++++++------ .../flutter/lib/src/material/drop_down.dart | 117 ++++++++---- .../flutter/lib/src/material/icon_button.dart | 19 +- .../src/material/paginated_data_table.dart | 166 ++++++++++++++---- .../flutter/lib/src/widgets/framework.dart | 4 +- .../flutter/lib/src/widgets/navigator.dart | 17 ++ packages/flutter/lib/src/widgets/routes.dart | 36 +++- .../flutter/lib/src/widgets/scrollable.dart | 23 ++- 8 files changed, 344 insertions(+), 147 deletions(-) diff --git a/examples/flutter_gallery/lib/demo/data_table_demo.dart b/examples/flutter_gallery/lib/demo/data_table_demo.dart index 3565eb7c0d..6756e4c05f 100644 --- a/examples/flutter_gallery/lib/demo/data_table_demo.dart +++ b/examples/flutter_gallery/lib/demo/data_table_demo.dart @@ -121,7 +121,7 @@ class DesertDataSource extends DataTableSource { int get rowCount => _deserts.length; @override - bool get isRowCountApproximate => true; + bool get isRowCountApproximate => false; } class DataTableDemo extends StatefulWidget { @@ -132,6 +132,7 @@ class DataTableDemo extends StatefulWidget { } class _DataTableDemoState extends State { + int _rowsPerPage = PaginatedDataTable.defaultRowsPerPage; int _sortColumnIndex; bool _sortAscending = true; DesertDataSource _deserts = new DesertDataSource(); @@ -149,63 +150,57 @@ class _DataTableDemoState extends State { return new Scaffold( appBar: new AppBar(title: new Text('Data tables')), body: new Block( + padding: const EdgeInsets.all(20.0), children: [ - new IntrinsicHeight( - child: new Block( - padding: const EdgeInsets.all(20.0), - scrollDirection: Axis.horizontal, - children: [ - new PaginatedDataTable( - rowsPerPage: 10, - sortColumnIndex: _sortColumnIndex, - sortAscending: _sortAscending, - columns: [ - new DataColumn( - label: new Text('Dessert (100g serving)'), - onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.name, columnIndex, ascending) - ), - new DataColumn( - label: new Text('Calories'), - tooltip: 'The total amount of food energy in the given serving size.', - numeric: true, - onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.calories, columnIndex, ascending) - ), - new DataColumn( - label: new Text('Fat (g)'), - numeric: true, - onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.fat, columnIndex, ascending) - ), - new DataColumn( - label: new Text('Carbs (g)'), - numeric: true, - onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.carbs, columnIndex, ascending) - ), - new DataColumn( - label: new Text('Protein (g)'), - numeric: true, - onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.protein, columnIndex, ascending) - ), - new DataColumn( - label: new Text('Sodium (mg)'), - numeric: true, - onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.sodium, columnIndex, ascending) - ), - new DataColumn( - label: new Text('Calcium (%)'), - tooltip: 'The amount of calcium as a percentage of the recommended daily amount.', - numeric: true, - onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.calcium, columnIndex, ascending) - ), - new DataColumn( - label: new Text('Iron (%)'), - numeric: true, - onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.iron, columnIndex, ascending) - ), - ], - source: _deserts - ) - ] - ) + new PaginatedDataTable( + rowsPerPage: _rowsPerPage, + onRowsPerPageChanged: (int value) { setState(() { _rowsPerPage = value; }); }, + sortColumnIndex: _sortColumnIndex, + sortAscending: _sortAscending, + columns: [ + new DataColumn( + label: new Text('Dessert (100g serving)'), + onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.name, columnIndex, ascending) + ), + new DataColumn( + label: new Text('Calories'), + tooltip: 'The total amount of food energy in the given serving size.', + numeric: true, + onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.calories, columnIndex, ascending) + ), + new DataColumn( + label: new Text('Fat (g)'), + numeric: true, + onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.fat, columnIndex, ascending) + ), + new DataColumn( + label: new Text('Carbs (g)'), + numeric: true, + onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.carbs, columnIndex, ascending) + ), + new DataColumn( + label: new Text('Protein (g)'), + numeric: true, + onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.protein, columnIndex, ascending) + ), + new DataColumn( + label: new Text('Sodium (mg)'), + numeric: true, + onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.sodium, columnIndex, ascending) + ), + new DataColumn( + label: new Text('Calcium (%)'), + tooltip: 'The amount of calcium as a percentage of the recommended daily amount.', + numeric: true, + onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.calcium, columnIndex, ascending) + ), + new DataColumn( + label: new Text('Iron (%)'), + numeric: true, + onSort: (int columnIndex, bool ascending) => _sort/**/((Desert d) => d.iron, columnIndex, ascending) + ), + ], + source: _deserts ) ] ) diff --git a/packages/flutter/lib/src/material/drop_down.dart b/packages/flutter/lib/src/material/drop_down.dart index ba5cbbcc8e..bf137b09f5 100644 --- a/packages/flutter/lib/src/material/drop_down.dart +++ b/packages/flutter/lib/src/material/drop_down.dart @@ -16,7 +16,6 @@ import 'theme.dart'; import 'material.dart'; const Duration _kDropDownMenuDuration = const Duration(milliseconds: 300); -const double _kTopMargin = 6.0; const double _kMenuItemHeight = 48.0; const EdgeInsets _kMenuVerticalPadding = const EdgeInsets.symmetric(vertical: 8.0); const EdgeInsets _kMenuHorizontalPadding = const EdgeInsets.symmetric(horizontal: 36.0); @@ -136,6 +135,7 @@ class _DropDownMenu extends StatusTransitionWidget { ), child: new Material( type: MaterialType.transparency, + textStyle: route.style, child: new ScrollableList( padding: _kMenuVerticalPadding, itemExtent: _kMenuItemHeight, @@ -182,8 +182,17 @@ class _DropDownMenuRouteLayout extends SingleChildLayoutDelegate { bottom = math.max(buttonTop + _kMenuItemHeight, bottomPreferredLimit); top = bottom - childSize.height; } - assert(top >= 0.0); - assert(top + childSize.height <= size.height); + assert(() { + final Rect container = Point.origin & size; + if (container.intersect(buttonRect) == buttonRect) { + // If the button was entirely on-screen, then verify + // that the menu is also on-screen. + // If the button was a bit off-screen, then, oh well. + assert(top >= 0.0); + assert(top + childSize.height <= size.height); + } + return true; + }); return new Offset(buttonRect.left, top); } @@ -220,14 +229,28 @@ class _DropDownRoute extends PopupRoute<_DropDownRouteResult> { this.items, this.buttonRect, this.selectedIndex, - this.elevation: 8 - }) : super(completer: completer); + this.elevation: 8, + TextStyle style + }) : _style = style, super(completer: completer) { + assert(style != null); + } final List> items; final Rect buttonRect; final int selectedIndex; final int elevation; + TextStyle get style => _style; + TextStyle _style; + set style (TextStyle value) { + assert(value != null); + if (_style == value) + return; + setState(() { + _style = value; + }); + } + @override Duration get transitionDuration => _kDropDownMenuDuration; @@ -277,13 +300,10 @@ class DropDownMenuItem extends StatelessWidget { return new Container( height: _kMenuItemHeight, padding: const EdgeInsets.symmetric(horizontal: 8.0), - child: new DefaultTextStyle( - style: Theme.of(context).textTheme.subhead, - child: new Baseline( - baselineType: TextBaseline.alphabetic, - baseline: _kMenuItemHeight - _kBaselineOffsetFromBottom, - child: child - ) + child: new Baseline( + baselineType: TextBaseline.alphabetic, + baseline: _kMenuItemHeight - _kBaselineOffsetFromBottom, + child: child ) ); } @@ -332,12 +352,17 @@ class DropDownButton extends StatefulWidget { /// Creates a drop down button. /// /// The [items] must have distinct values and [value] must be among them. + /// + /// The [elevation] and [iconSize] arguments must not be null (they both have + /// defaults, so do not need to be specified). DropDownButton({ Key key, this.items, this.value, this.onChanged, - this.elevation: 8 + this.elevation: 8, + this.style, + this.iconSize: 36.0 }) : super(key: key) { assert(items != null); assert(items.where((DropDownMenuItem item) => item.value == value).length == 1); @@ -357,6 +382,18 @@ class DropDownButton extends StatefulWidget { /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12, 16, 24 final int elevation; + /// The text style to use for text in the drop down button and the drop down + /// menu that appears when you tap the button. + /// + /// Defaults to the [TextTheme.subhead] value of the current + /// [ThemeData.textTheme] of the current [Theme]. + final TextStyle style; + + /// The size to use for the drop-down button's down arrow icon button. + /// + /// Defaults to 36.0. + final double iconSize; + @override _DropDownButtonState createState() => new _DropDownButtonState(); } @@ -388,18 +425,26 @@ class _DropDownButtonState extends State> { } } + TextStyle get _textStyle => config.style ?? Theme.of(context).textTheme.subhead; + + _DropDownRoute _currentRoute; + void _handleTap() { + assert(_currentRoute == null); final RenderBox itemBox = _itemKey.currentContext.findRenderObject(); final Rect itemRect = itemBox.localToGlobal(Point.origin) & itemBox.size; final Completer<_DropDownRouteResult> completer = new Completer<_DropDownRouteResult>(); - Navigator.push(context, new _DropDownRoute( + _currentRoute = new _DropDownRoute( completer: completer, items: config.items, buttonRect: _kMenuHorizontalPadding.inflateRect(itemRect), selectedIndex: _selectedIndex, - elevation: config.elevation - )); + elevation: config.elevation, + style: _textStyle + ); + Navigator.push(context, _currentRoute); completer.future.then((_DropDownRouteResult newValue) { + _currentRoute = null; if (!mounted || newValue == null) return; if (config.onChanged != null) @@ -410,28 +455,28 @@ class _DropDownButtonState extends State> { @override Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); - Widget result = new Row( - mainAxisAlignment: MainAxisAlignment.collapse, - children: [ - // We use an IndexedStack to make sure we have enough width to show any - // possible item as the selected item without changing size. - new IndexedStack( - children: config.items, - key: _itemKey, - index: _selectedIndex, - alignment: FractionalOffset.centerLeft - ), - new Icon(icon: Icons.arrow_drop_down, size: 36.0) - ] + final TextStyle style = _textStyle; + if (_currentRoute != null) + _currentRoute.style = style; + Widget result = new DefaultTextStyle( + style: style, + child: new Row( + mainAxisAlignment: MainAxisAlignment.collapse, + children: [ + // We use an IndexedStack to make sure we have enough width to show any + // possible item as the selected item without changing size. + new IndexedStack( + key: _itemKey, + index: _selectedIndex, + alignment: FractionalOffset.centerLeft, + children: config.items + ), + new Icon(icon: Icons.arrow_drop_down, size: config.iconSize) + ] + ) ); - if (DropDownButtonHideUnderline.at(context)) { - result = new Padding( - padding: const EdgeInsets.only(top: _kTopMargin, bottom: _kBottomBorderHeight), - child: result - ); - } else { + if (!DropDownButtonHideUnderline.at(context)) { result = new Container( - padding: const EdgeInsets.only(top: _kTopMargin), decoration: const BoxDecoration(border: _kDropDownUnderline), child: result ); diff --git a/packages/flutter/lib/src/material/icon_button.dart b/packages/flutter/lib/src/material/icon_button.dart index f202e5c737..a07d6c190c 100644 --- a/packages/flutter/lib/src/material/icon_button.dart +++ b/packages/flutter/lib/src/material/icon_button.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'package:flutter/widgets.dart'; +import 'package:meta/meta.dart'; import 'debug.dart'; import 'icon.dart'; @@ -35,12 +36,18 @@ class IconButton extends StatelessWidget { /// be used in many other places as well. /// /// Requires one of its ancestors to be a [Material] widget. + /// + /// The [size], [padding], and [alignment] arguments must not be null (though + /// they each have default values). + /// + /// The [icon] argument must be specified. See [Icons] for a list of icons to + /// use for this argument. const IconButton({ Key key, this.size: 24.0, this.padding: const EdgeInsets.all(8.0), this.alignment: FractionalOffset.center, - this.icon, + @required this.icon, this.color, this.disabledColor, this.onPressed, @@ -48,16 +55,24 @@ class IconButton extends StatelessWidget { }) : super(key: key); /// The size of the icon inside the button. + /// + /// This property must not be null. It defaults to 24.0. final double size; /// The padding around the button's icon. The entire padded icon will react /// to input gestures. + /// + /// This property must not be null. It defaults to 8.0 padding on all sides. final EdgeInsets padding; /// Defines how the icon is positioned within the IconButton. + /// + /// This property must not be null. It defaults to [FractionalOffset.center]. final FractionalOffset alignment; - /// The icon to display inside the button. + /// The icon to display inside the button, from the list in [Icons]. + /// + /// This property must not be null. final IconData icon; /// The color to use for the icon inside the button, if the icon is enabled. diff --git a/packages/flutter/lib/src/material/paginated_data_table.dart b/packages/flutter/lib/src/material/paginated_data_table.dart index a8d2e36b90..7a1fd2be20 100644 --- a/packages/flutter/lib/src/material/paginated_data_table.dart +++ b/packages/flutter/lib/src/material/paginated_data_table.dart @@ -2,12 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:math' as math; + import 'package:flutter/widgets.dart'; +import 'package:flutter/rendering.dart'; import 'card.dart'; import 'data_table.dart'; import 'data_table_source.dart'; +import 'drop_down.dart'; +import 'icon_button.dart'; +import 'icon_theme.dart'; +import 'icon_theme_data.dart'; +import 'icons.dart'; import 'progress_indicator.dart'; +import 'theme.dart'; /// A wrapper for [DataTable] that obtains data lazily from a [DataTableSource] /// and displays it one page at a time. The widget is presented as a [Card]. @@ -33,6 +42,9 @@ class PaginatedDataTable extends StatefulWidget { /// [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. + /// + /// The [rowsPerPage] and [availableRowsPerPage] must not be null (though they + /// both have defaults, so don't have to be specified). PaginatedDataTable({ Key key, this.columns, @@ -41,7 +53,8 @@ class PaginatedDataTable extends StatefulWidget { this.onSelectAll, this.initialFirstRowIndex: 0, this.onPageChanged, - this.rowsPerPage: 10, + this.rowsPerPage: defaultRowsPerPage, + this.availableRowsPerPage: const [defaultRowsPerPage, defaultRowsPerPage * 2, defaultRowsPerPage * 5, defaultRowsPerPage * 10], this.onRowsPerPageChanged, this.source }) : super(key: key) { @@ -49,6 +62,10 @@ class PaginatedDataTable extends StatefulWidget { assert(columns.length > 0); assert(sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length)); assert(sortAscending != null); + assert(rowsPerPage != null); + assert(rowsPerPage > 0); + assert(availableRowsPerPage != null); + assert(availableRowsPerPage.contains(rowsPerPage)); assert(source != null); } @@ -76,13 +93,31 @@ class PaginatedDataTable extends StatefulWidget { final int initialFirstRowIndex; /// Invoked when the user switches to another page. + /// + /// The value is the index of the first row on the currently displayed page. final ValueChanged onPageChanged; /// The number of rows to show on each page. /// - /// See also [onRowsPerPageChanged]. + /// See also: + /// + /// * [onRowsPerPageChanged] + /// * [defaultRowsPerPage] final int rowsPerPage; + /// 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 availableRowsPerPage; + /// 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 @@ -142,11 +177,15 @@ class PaginatedDataTableState extends State { } /// Ensures that the given row is visible. - void pageTo(double rowIndex) { + void pageTo(int rowIndex) { + final int oldFirstRowIndex = _firstRowIndex; setState(() { final int rowsPerPage = config.rowsPerPage; _firstRowIndex = (rowIndex ~/ rowsPerPage) * rowsPerPage; }); + if ((config.onPageChanged != null) && + (oldFirstRowIndex != _firstRowIndex)) + config.onPageChanged(_firstRowIndex); } DataRow _getBlankRowFor(int index) { @@ -198,40 +237,97 @@ class PaginatedDataTableState extends State { @override Widget build(BuildContext context) { - final List rows = _getRows(_firstRowIndex, config.rowsPerPage); - Widget table = new DataTable( - key: _tableKey, - columns: config.columns, - sortColumnIndex: config.sortColumnIndex, - sortAscending: config.sortAscending, - onSelectAll: config.onSelectAll, - rows: rows - ); + final TextStyle textStyle = Theme.of(context).textTheme.caption; + final List footerWidgets = []; + if (config.onRowsPerPageChanged != null) { + List availableRowsPerPage = config.availableRowsPerPage + .where((int value) => value <= _rowCount) + .map/*>*/((int value) { + return new DropDownMenuItem( + value: value, + child: new Text('$value') + ); + }) + .toList(); + footerWidgets.addAll([ + new Text('Rows per page:'), + new DropDownButtonHideUnderline( + child: new DropDownButton( + items: availableRowsPerPage, + value: config.rowsPerPage, + onChanged: config.onRowsPerPageChanged, + style: textStyle, + iconSize: 24.0 + ) + ), + ]); + } + footerWidgets.addAll([ + 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( + padding: EdgeInsets.zero, + icon: Icons.chevron_left, + onPressed: _firstRowIndex <= 0 ? null : () { + pageTo(math.max(_firstRowIndex - config.rowsPerPage, 0)); + } + ), + new Container(width: 24.0), + new IconButton( + padding: EdgeInsets.zero, + icon: Icons.chevron_right, + onPressed: (!_rowCountApproximate && (_firstRowIndex + config.rowsPerPage >= _rowCount)) ? null : () { + pageTo(_firstRowIndex + config.rowsPerPage); + } + ), + new Container(width: 14.0), + ]); return new Card( // TODO(ianh): data table card headers - child: table - // TODO(ianh): data table card footers: prev/next page, rows per page, etc + /* + - title, top left + - 20px Roboto Regular, black87 + - persistent actions, top left + - header when there's a selection + - accent 50? + - show number of selected items + - different actions + - actions, top right + - 24px icons, black54 + */ + child: new BlockBody( + children: [ + new ScrollableViewport( + 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( + style: textStyle, + child: new IconTheme( + data: new IconThemeData( + opacity: 0.54 + ), + child: new Container( + height: 56.0, + child: new Row( + mainAxisAlignment: MainAxisAlignment.end, + children: footerWidgets + ) + ) + ) + ) + ] + ) ); } } - -/* - -DataTableCard - - top: 64px - - caption, top left - - 20px Roboto Regular, black87 - - persistent actions, top left - - header when there's a selection - - accent 50? - - show number of selected items - - different actions - - actions, top right - - 24px icons, black54 - -bottom: - - 56px - - handles pagination - - 12px Roboto Regular, black54 - -*/ diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 0f4cc3ea8f..571bb7caee 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -400,7 +400,9 @@ abstract class State { /// Whenever you need to change internal state for a State object, make the /// change in a function that you pass to setState(), as in: /// - /// setState(() { myState = newValue }); + /// ```dart + /// setState(() { myState = newValue }); + /// ``` /// /// If you just change the state directly without calling setState(), then the /// widget will not be scheduled for rebuilding, meaning that its rendering diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index aadaa41209..0021c1b687 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -71,12 +71,29 @@ abstract class Route { void dispose() { } /// Whether this route is the top-most route on the navigator. + /// + /// If this is true, then [isActive] is also true. bool get isCurrent { if (_navigator == null) return false; assert(_navigator._history.contains(this)); return _navigator._history.last == this; } + + /// Whether this route is on the navigator. + /// + /// If the route is not only active, but also the current route (the top-most + /// route), then [isCurrent] will also be true. + /// + /// If a later route is entirely opaque, then the route will be active but not + /// rendered. In particular, it's possible for a route to be active but for + /// stateful widgets within the route to not be instantiated. + bool get isActive { + if (_navigator == null) + return false; + assert(_navigator._history.contains(this)); + return true; + } } /// Data that might be useful in constructing a [Route]. diff --git a/packages/flutter/lib/src/widgets/routes.dart b/packages/flutter/lib/src/widgets/routes.dart index 35d50bb0d1..240aea0472 100644 --- a/packages/flutter/lib/src/widgets/routes.dart +++ b/packages/flutter/lib/src/widgets/routes.dart @@ -4,6 +4,8 @@ import 'dart:async'; +import 'package:meta/meta.dart'; + import 'basic.dart'; import 'focus.dart'; import 'framework.dart'; @@ -400,11 +402,8 @@ class _ModalScopeState extends State<_ModalScope> { }); } - void _didChangeRouteOffStage() { - setState(() { - // We use the route's offstage bool in our build function, which means our - // state has changed. - }); + void _routeSetState(VoidCallback fn) { + setState(fn); } @override @@ -466,6 +465,28 @@ abstract class ModalRoute extends TransitionRoute with LocalHistoryRoute extends TransitionRoute with LocalHistoryRoute