paginated_data_table_test.dart 37.6 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 7 8 9 10
// TODO(gspencergoog): Remove this tag once this test's state leaks/test
// dependencies have been fixed.
// https://github.com/flutter/flutter/issues/85160
// Fails with "flutter test --test-randomize-ordering-seed=1000"
@Tags(<String>['no-shuffle'])

11
import 'package:flutter/gestures.dart' show DragStartBehavior;
12
import 'package:flutter/material.dart';
13
import 'package:flutter/rendering.dart';
14 15
import 'package:flutter_test/flutter_test.dart';

16
import 'data_table_test_utils.dart';
17 18

class TestDataSource extends DataTableSource {
19
  TestDataSource({
20
    this.allowSelection = false,
21 22
  });

23
  final bool allowSelection;
24

25 26 27
  int get generation => _generation;
  int _generation = 0;
  set generation(int value) {
28
    if (_generation == value) {
29
      return;
30
    }
31 32 33 34
    _generation = value;
    notifyListeners();
  }

35 36 37
  final Set<int> _selectedRows = <int>{};

  void _handleSelected(int index, bool? selected) {
38
    if (selected ?? false) {
39 40 41 42 43 44 45
      _selectedRows.add(index);
    } else {
      _selectedRows.remove(index);
    }
    notifyListeners();
  }

46 47 48 49
  @override
  DataRow getRow(int index) {
    final Dessert dessert = kDesserts[index % kDesserts.length];
    final int page = index ~/ kDesserts.length;
50
    return DataRow.byIndex(
51
      index: index,
52
      selected: _selectedRows.contains(index),
53
      cells: <DataCell>[
54 55 56
        DataCell(Text('${dessert.name} ($page)')),
        DataCell(Text('${dessert.calories}')),
        DataCell(Text('$generation')),
57
      ],
58
      onSelectChanged: allowSelection ? (bool? selected) => _handleSelected(index, selected) : null,
59 60 61 62
    );
  }

  @override
63
  int get rowCount => 50 * kDesserts.length;
64 65 66 67 68

  @override
  bool get isRowCountApproximate => false;

  @override
69
  int get selectedRowCount => _selectedRows.length;
70 71 72
}

void main() {
73
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
74

75
  testWidgets('PaginatedDataTable paging', (WidgetTester tester) async {
76
    final TestDataSource source = TestDataSource();
77

78
    final List<String> log = <String>[];
79

80 81
    await tester.pumpWidget(MaterialApp(
      home: PaginatedDataTable(
82
        header: const Text('Test table'),
83 84
        source: source,
        rowsPerPage: 2,
85
        showFirstLastButtons: true,
86
        availableRowsPerPage: const <int>[
87 88
          2, 4, 8, 16,
        ],
89
        onRowsPerPageChanged: (int? rowsPerPage) {
90 91 92 93 94
          log.add('rows-per-page-changed: $rowsPerPage');
        },
        onPageChanged: (int rowIndex) {
          log.add('page-changed: $rowIndex');
        },
95
        columns: const <DataColumn>[
96 97 98
          DataColumn(label: Text('Name')),
          DataColumn(label: Text('Calories'), numeric: true),
          DataColumn(label: Text('Generation')),
99
        ],
100
      ),
101 102 103 104 105 106 107 108 109 110 111 112 113
    ));

    await tester.tap(find.byTooltip('Next page'));

    expect(log, <String>['page-changed: 2']);
    log.clear();

    await tester.pump();

    expect(find.text('Frozen yogurt (0)'), findsNothing);
    expect(find.text('Eclair (0)'), findsOneWidget);
    expect(find.text('Gingerbread (0)'), findsNothing);

114
    await tester.tap(find.byIcon(Icons.chevron_left));
115 116 117 118 119 120 121 122 123 124

    expect(log, <String>['page-changed: 0']);
    log.clear();

    await tester.pump();

    expect(find.text('Frozen yogurt (0)'), findsOneWidget);
    expect(find.text('Eclair (0)'), findsNothing);
    expect(find.text('Gingerbread (0)'), findsNothing);

125 126 127 128
    final Finder lastPageButton = find.ancestor(
      of: find.byTooltip('Last page'),
      matching: find.byWidgetPredicate((Widget widget) => widget is IconButton),
    );
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

    expect(tester.widget<IconButton>(lastPageButton).onPressed, isNotNull);

    await tester.tap(lastPageButton);

    expect(log, <String>['page-changed: 498']);
    log.clear();

    await tester.pump();

    expect(tester.widget<IconButton>(lastPageButton).onPressed, isNull);

    expect(find.text('Frozen yogurt (0)'), findsNothing);
    expect(find.text('Donut (49)'), findsOneWidget);
    expect(find.text('KitKat (49)'), findsOneWidget);

145 146 147 148
    final Finder firstPageButton = find.ancestor(
      of: find.byTooltip('First page'),
      matching: find.byWidgetPredicate((Widget widget) => widget is IconButton),
    );
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164

    expect(tester.widget<IconButton>(firstPageButton).onPressed, isNotNull);

    await tester.tap(firstPageButton);

    expect(log, <String>['page-changed: 0']);
    log.clear();

    await tester.pump();

    expect(tester.widget<IconButton>(firstPageButton).onPressed, isNull);

    expect(find.text('Frozen yogurt (0)'), findsOneWidget);
    expect(find.text('Eclair (0)'), findsNothing);
    expect(find.text('Gingerbread (0)'), findsNothing);

165
    await tester.tap(find.byIcon(Icons.chevron_left));
166 167 168 169

    expect(log, isEmpty);

    await tester.tap(find.text('2'));
170
    await tester.pumpAndSettle(const Duration(milliseconds: 200));
171 172

    await tester.tap(find.text('8').last);
173
    await tester.pumpAndSettle(const Duration(milliseconds: 200));
174 175 176 177 178

    expect(log, <String>['rows-per-page-changed: 8']);
    log.clear();
  });

179
  testWidgets('PaginatedDataTable control test', (WidgetTester tester) async {
180
    TestDataSource source = TestDataSource()
181 182
      ..generation = 42;

183
    final List<String> log = <String>[];
184 185

    Widget buildTable(TestDataSource source) {
186
      return PaginatedDataTable(
187
        header: const Text('Test table'),
188 189 190 191 192
        source: source,
        onPageChanged: (int rowIndex) {
          log.add('page-changed: $rowIndex');
        },
        columns: <DataColumn>[
193
          const DataColumn(
194
            label: Text('Name'),
195 196
            tooltip: 'Name',
          ),
197
          DataColumn(
198
            label: const Text('Calories'),
199 200 201 202
            tooltip: 'Calories',
            numeric: true,
            onSort: (int columnIndex, bool ascending) {
              log.add('column-sort: $columnIndex $ascending');
203
            },
204
          ),
205
          const DataColumn(
206
            label: Text('Generation'),
207 208 209 210
            tooltip: 'Generation',
          ),
        ],
        actions: <Widget>[
211
          IconButton(
212
            icon: const Icon(Icons.adjust),
213 214 215 216 217 218 219 220
            onPressed: () {
              log.add('action: adjust');
            },
          ),
        ],
      );
    }

221
    await tester.pumpWidget(MaterialApp(
222 223 224
      home: buildTable(source),
    ));

225
    // the column overflows because we're forcing it to 600 pixels high
226
    final dynamic exception = tester.takeException();
Dan Field's avatar
Dan Field committed
227
    expect(exception, isFlutterError);
228
    // ignore: avoid_dynamic_calls
229
    expect(exception.diagnostics.first.level, DiagnosticLevel.summary);
230
    // ignore: avoid_dynamic_calls
231
    expect(exception.diagnostics.first.toString(), startsWith('A RenderFlex overflowed by '));
232

233 234
    expect(find.text('Gingerbread (0)'), findsOneWidget);
    expect(find.text('Gingerbread (1)'), findsNothing);
235 236 237 238 239 240 241 242
    expect(find.text('42'), findsNWidgets(10));

    source.generation = 43;
    await tester.pump();

    expect(find.text('42'), findsNothing);
    expect(find.text('43'), findsNWidgets(10));

243
    source = TestDataSource()
244 245
      ..generation = 15;

246
    await tester.pumpWidget(MaterialApp(
247 248 249 250 251 252 253
      home: buildTable(source),
    ));

    expect(find.text('42'), findsNothing);
    expect(find.text('43'), findsNothing);
    expect(find.text('15'), findsNWidgets(10));

254
    final PaginatedDataTableState state = tester.state(find.byType(PaginatedDataTable));
255 256 257 258 259 260 261 262

    expect(log, isEmpty);
    state.pageTo(23);
    expect(log, <String>['page-changed: 20']);
    log.clear();

    await tester.pump();

263 264 265
    expect(find.text('Gingerbread (0)'), findsNothing);
    expect(find.text('Gingerbread (1)'), findsNothing);
    expect(find.text('Gingerbread (2)'), findsOneWidget);
266

267
    await tester.tap(find.byIcon(Icons.adjust));
268 269 270
    expect(log, <String>['action: adjust']);
    log.clear();
  });
271 272

  testWidgets('PaginatedDataTable text alignment', (WidgetTester tester) async {
273 274
    await tester.pumpWidget(MaterialApp(
      home: PaginatedDataTable(
275
        header: const Text('HEADER'),
276
        source: TestDataSource(),
277
        rowsPerPage: 8,
278
        availableRowsPerPage: const <int>[
279 280
          8, 9,
        ],
281
        onRowsPerPageChanged: (int? rowsPerPage) { },
282
        columns: const <DataColumn>[
283 284 285
          DataColumn(label: Text('COL1')),
          DataColumn(label: Text('COL2')),
          DataColumn(label: Text('COL3')),
286 287 288 289 290 291 292 293
        ],
      ),
    ));
    expect(find.text('Rows per page:'), findsOneWidget);
    expect(find.text('8'), findsOneWidget);
    expect(tester.getTopRight(find.text('8')).dx, tester.getTopRight(find.text('Rows per page:')).dx + 40.0); // per spec
  });

294 295 296 297 298 299 300 301 302 303
  testWidgets('PaginatedDataTable with and without header and actions', (WidgetTester tester) async {
    await binding.setSurfaceSize(const Size(800, 800));
    const String headerText = 'HEADER';
    final List<Widget> actions = <Widget>[
      IconButton(onPressed: () {}, icon: const Icon(Icons.add)),
    ];
    Widget buildTable({String? header, List<Widget>? actions}) => MaterialApp(
      home: PaginatedDataTable(
        header: header != null ? Text(header) : null,
        actions: actions,
304
        source: TestDataSource(allowSelection: true),
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
        columns: const <DataColumn>[
          DataColumn(label: Text('Name')),
          DataColumn(label: Text('Calories'), numeric: true),
          DataColumn(label: Text('Generation')),
        ],
      ),
    );

    await tester.pumpWidget(buildTable(header: headerText));
    expect(find.text(headerText), findsOneWidget);
    expect(find.byIcon(Icons.add), findsNothing);

    await tester.pumpWidget(buildTable(header: headerText, actions: actions));
    expect(find.text(headerText), findsOneWidget);
    expect(find.byIcon(Icons.add), findsOneWidget);

    await tester.pumpWidget(buildTable());
    expect(find.text(headerText), findsNothing);
    expect(find.byIcon(Icons.add), findsNothing);

    expect(() => buildTable(actions: actions), throwsAssertionError);

    await binding.setSurfaceSize(null);
  });

330
  testWidgets('PaginatedDataTable with large text', (WidgetTester tester) async {
331 332 333
    final TestDataSource source = TestDataSource();
    await tester.pumpWidget(MaterialApp(
      home: MediaQuery(
334 335 336
        data: const MediaQueryData(
          textScaleFactor: 20.0,
        ),
337
        child: PaginatedDataTable(
338 339 340
          header: const Text('HEADER'),
          source: source,
          rowsPerPage: 501,
341
          availableRowsPerPage: const <int>[ 501 ],
342
          onRowsPerPageChanged: (int? rowsPerPage) { },
343
          columns: const <DataColumn>[
344 345 346
            DataColumn(label: Text('COL1')),
            DataColumn(label: Text('COL2')),
            DataColumn(label: Text('COL3')),
347 348 349 350 351
          ],
        ),
      ),
    ));
    // the column overflows because we're forcing it to 600 pixels high
352
    final dynamic exception = tester.takeException();
Dan Field's avatar
Dan Field committed
353
    expect(exception, isFlutterError);
354
    // ignore: avoid_dynamic_calls
355
    expect(exception.diagnostics.first.level, DiagnosticLevel.summary);
356
    // ignore: avoid_dynamic_calls
357 358
    expect(exception.diagnostics.first.toString(), contains('A RenderFlex overflowed by'));

359 360 361 362 363 364
    expect(find.text('Rows per page:'), findsOneWidget);
    // Test that we will show some options in the drop down even if the lowest option is bigger than the source:
    assert(501 > source.rowCount);
    expect(find.text('501'), findsOneWidget);
    // Test that it fits:
    expect(tester.getTopRight(find.text('501')).dx, greaterThanOrEqualTo(tester.getTopRight(find.text('Rows per page:')).dx + 40.0));
365
  }, skip: isBrowser);  // https://github.com/flutter/flutter/issues/43433
366 367

  testWidgets('PaginatedDataTable footer scrolls', (WidgetTester tester) async {
368
    final TestDataSource source = TestDataSource();
369 370 371 372 373 374 375 376 377 378 379 380
    await tester.pumpWidget(
      MaterialApp(
        home: Align(
          alignment: Alignment.topLeft,
          child: SizedBox(
            width: 100.0,
            child: PaginatedDataTable(
              header: const Text('HEADER'),
              source: source,
              rowsPerPage: 5,
              dragStartBehavior: DragStartBehavior.down,
              availableRowsPerPage: const <int>[ 5 ],
381
              onRowsPerPageChanged: (int? rowsPerPage) { },
382 383 384 385 386 387
              columns: const <DataColumn>[
                DataColumn(label: Text('COL1')),
                DataColumn(label: Text('COL2')),
                DataColumn(label: Text('COL3')),
              ],
            ),
388 389 390
          ),
        ),
      ),
391
    );
392 393 394
    expect(find.text('Rows per page:'), findsOneWidget);
    expect(tester.getTopLeft(find.text('Rows per page:')).dx, lessThan(0.0)); // off screen
    await tester.dragFrom(
395
      Offset(50.0, tester.getTopLeft(find.text('Rows per page:')).dy),
396 397 398 399 400 401
      const Offset(1000.0, 0.0),
    );
    await tester.pump();
    expect(find.text('Rows per page:'), findsOneWidget);
    expect(tester.getTopLeft(find.text('Rows per page:')).dx, 18.0); // 14 padding in the footer row, 4 padding from the card
  });
402

403 404 405 406 407 408 409 410 411 412 413 414 415 416
  testWidgets('PaginatedDataTable custom row height', (WidgetTester tester) async {
    final TestDataSource source = TestDataSource();

    Widget buildCustomHeightPaginatedTable({
      double dataRowHeight = 48.0,
      double headingRowHeight = 56.0,
    }) {
      return PaginatedDataTable(
        header: const Text('Test table'),
        source: source,
        rowsPerPage: 2,
        availableRowsPerPage: const <int>[
          2, 4, 8, 16,
        ],
417
        onRowsPerPageChanged: (int? rowsPerPage) {},
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
        onPageChanged: (int rowIndex) {},
        columns: const <DataColumn>[
          DataColumn(label: Text('Name')),
          DataColumn(label: Text('Calories'), numeric: true),
          DataColumn(label: Text('Generation')),
        ],
        dataRowHeight: dataRowHeight,
        headingRowHeight: headingRowHeight,
      );
    }

    // DEFAULT VALUES
    await tester.pumpWidget(MaterialApp(
      home: PaginatedDataTable(
        header: const Text('Test table'),
        source: source,
        rowsPerPage: 2,
        availableRowsPerPage: const <int>[
          2, 4, 8, 16,
        ],
438
        onRowsPerPageChanged: (int? rowsPerPage) {},
439 440 441 442 443 444 445 446 447
        onPageChanged: (int rowIndex) {},
        columns: const <DataColumn>[
          DataColumn(label: Text('Name')),
          DataColumn(label: Text('Calories'), numeric: true),
          DataColumn(label: Text('Generation')),
        ],
      ),
    ));
    expect(tester.renderObject<RenderBox>(
448
      find.widgetWithText(Container, 'Name').first,
449 450
    ).size.height, 56.0); // This is the header row height
    expect(tester.renderObject<RenderBox>(
451
      find.widgetWithText(Container, 'Frozen yogurt (0)').first,
452 453 454 455 456 457 458
    ).size.height, 48.0); // This is the data row height

    // CUSTOM VALUES
    await tester.pumpWidget(MaterialApp(
      home: Material(child: buildCustomHeightPaginatedTable(headingRowHeight: 48.0)),
    ));
    expect(tester.renderObject<RenderBox>(
459
      find.widgetWithText(Container, 'Name').first,
460 461 462 463 464 465
    ).size.height, 48.0);

    await tester.pumpWidget(MaterialApp(
      home: Material(child: buildCustomHeightPaginatedTable(headingRowHeight: 64.0)),
    ));
    expect(tester.renderObject<RenderBox>(
466
      find.widgetWithText(Container, 'Name').first,
467 468 469 470 471 472
    ).size.height, 64.0);

    await tester.pumpWidget(MaterialApp(
      home: Material(child: buildCustomHeightPaginatedTable(dataRowHeight: 30.0)),
    ));
    expect(tester.renderObject<RenderBox>(
473
      find.widgetWithText(Container, 'Frozen yogurt (0)').first,
474 475 476 477 478 479
    ).size.height, 30.0);

    await tester.pumpWidget(MaterialApp(
      home: Material(child: buildCustomHeightPaginatedTable(dataRowHeight: 56.0)),
    ));
    expect(tester.renderObject<RenderBox>(
480
      find.widgetWithText(Container, 'Frozen yogurt (0)').first,
481 482
    ).size.height, 56.0);
  });
483 484

  testWidgets('PaginatedDataTable custom horizontal padding - checkbox', (WidgetTester tester) async {
485 486 487 488
    const double defaultHorizontalMargin = 24.0;
    const double defaultColumnSpacing = 56.0;
    const double customHorizontalMargin = 10.0;
    const double customColumnSpacing = 15.0;
489

490 491
    const double width = 400;
    const double height = 400;
492 493 494 495 496

    final Size originalSize = binding.renderView.size;

    // Ensure the containing Card is small enough that we don't expand too
    // much, resulting in our custom margin being ignored.
497
    await binding.setSurfaceSize(const Size(width, height));
498

499
    final TestDataSource source = TestDataSource(allowSelection: true);
500 501 502 503 504 505 506 507 508 509 510 511
    Finder cellContent;
    Finder checkbox;
    Finder padding;

    await tester.pumpWidget(MaterialApp(
      home: PaginatedDataTable(
        header: const Text('Test table'),
        source: source,
        rowsPerPage: 2,
        availableRowsPerPage: const <int>[
          2, 4,
        ],
512
        onRowsPerPageChanged: (int? rowsPerPage) {},
513
        onPageChanged: (int rowIndex) {},
514
        onSelectAll: (bool? value) {},
515 516 517 518 519 520 521 522 523 524 525 526 527
        columns: const <DataColumn>[
          DataColumn(label: Text('Name')),
          DataColumn(label: Text('Calories'), numeric: true),
          DataColumn(label: Text('Generation')),
        ],
      ),
    ));

    // default checkbox padding
    checkbox = find.byType(Checkbox).first;
    padding = find.ancestor(of: checkbox, matching: find.byType(Padding)).first;
    expect(
      tester.getRect(checkbox).left - tester.getRect(padding).left,
528
      defaultHorizontalMargin,
529 530 531
    );
    expect(
      tester.getRect(padding).right - tester.getRect(checkbox).right,
532
      defaultHorizontalMargin / 2,
533 534 535 536 537 538 539
    );

    // default first column padding
    padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
    cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)'); // DataTable wraps its DataCells in an Align widget
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
540
      defaultHorizontalMargin / 2,
541 542 543
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
544
      defaultColumnSpacing / 2,
545 546 547 548 549 550 551
    );

    // default middle column padding
    padding = find.widgetWithText(Padding, '159').first;
    cellContent = find.widgetWithText(Align, '159');
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
552
      defaultColumnSpacing / 2,
553 554 555
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
556
      defaultColumnSpacing / 2,
557 558 559 560 561 562 563
    );

    // default last column padding
    padding = find.widgetWithText(Padding, '0').first;
    cellContent = find.widgetWithText(Align, '0').first;
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
564
      defaultColumnSpacing / 2,
565 566 567
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
568
      defaultHorizontalMargin,
569 570 571 572 573 574 575 576 577 578 579 580
    );

    // CUSTOM VALUES
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: PaginatedDataTable(
          header: const Text('Test table'),
          source: source,
          rowsPerPage: 2,
          availableRowsPerPage: const <int>[
            2, 4,
          ],
581
          onRowsPerPageChanged: (int? rowsPerPage) {},
582
          onPageChanged: (int rowIndex) {},
583
          onSelectAll: (bool? value) {},
584 585 586 587 588
          columns: const <DataColumn>[
            DataColumn(label: Text('Name')),
            DataColumn(label: Text('Calories'), numeric: true),
            DataColumn(label: Text('Generation')),
          ],
589 590
          horizontalMargin: customHorizontalMargin,
          columnSpacing: customColumnSpacing,
591 592 593 594 595 596 597 598 599
        ),
      ),
    ));

    // custom checkbox padding
    checkbox = find.byType(Checkbox).first;
    padding = find.ancestor(of: checkbox, matching: find.byType(Padding)).first;
    expect(
      tester.getRect(checkbox).left - tester.getRect(padding).left,
600
      customHorizontalMargin,
601 602 603
    );
    expect(
      tester.getRect(padding).right - tester.getRect(checkbox).right,
604
      customHorizontalMargin / 2,
605 606 607 608 609 610 611
    );

    // custom first column padding
    padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
    cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)'); // DataTable wraps its DataCells in an Align widget
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
612
      customHorizontalMargin / 2,
613 614 615
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
616
      customColumnSpacing / 2,
617 618 619 620 621 622 623
    );

    // custom middle column padding
    padding = find.widgetWithText(Padding, '159').first;
    cellContent = find.widgetWithText(Align, '159');
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
624
      customColumnSpacing / 2,
625 626 627
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
628
      customColumnSpacing / 2,
629 630 631 632 633 634 635
    );

    // custom last column padding
    padding = find.widgetWithText(Padding, '0').first;
    cellContent = find.widgetWithText(Align, '0').first;
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
636
      customColumnSpacing / 2,
637 638 639
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
640
      customHorizontalMargin,
641
    );
642 643 644

    // Reset the surface size.
    await binding.setSurfaceSize(originalSize);
645 646 647
  });

  testWidgets('PaginatedDataTable custom horizontal padding - no checkbox', (WidgetTester tester) async {
648 649 650 651
    const double defaultHorizontalMargin = 24.0;
    const double defaultColumnSpacing = 56.0;
    const double customHorizontalMargin = 10.0;
    const double customColumnSpacing = 15.0;
652 653 654 655 656 657 658 659 660 661 662 663
    final TestDataSource source = TestDataSource();
    Finder cellContent;
    Finder padding;

    await tester.pumpWidget(MaterialApp(
      home: PaginatedDataTable(
        header: const Text('Test table'),
        source: source,
        rowsPerPage: 2,
        availableRowsPerPage: const <int>[
          2, 4, 8, 16,
        ],
664
        onRowsPerPageChanged: (int? rowsPerPage) {},
665 666 667 668 669 670 671 672 673 674 675 676 677 678
        onPageChanged: (int rowIndex) {},
        columns: const <DataColumn>[
          DataColumn(label: Text('Name')),
          DataColumn(label: Text('Calories'), numeric: true),
          DataColumn(label: Text('Generation')),
        ],
      ),
    ));

    // default first column padding
    padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
    cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)'); // DataTable wraps its DataCells in an Align widget
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
679
      defaultHorizontalMargin,
680 681 682
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
683
      defaultColumnSpacing / 2,
684 685 686 687 688 689 690
    );

    // default middle column padding
    padding = find.widgetWithText(Padding, '159').first;
    cellContent = find.widgetWithText(Align, '159');
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
691
      defaultColumnSpacing / 2,
692 693 694
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
695
      defaultColumnSpacing / 2,
696 697 698 699 700 701 702
    );

    // default last column padding
    padding = find.widgetWithText(Padding, '0').first;
    cellContent = find.widgetWithText(Align, '0').first;
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
703
      defaultColumnSpacing / 2,
704 705 706
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
707
      defaultHorizontalMargin,
708 709 710 711 712 713 714 715 716 717 718 719
    );

    // CUSTOM VALUES
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: PaginatedDataTable(
          header: const Text('Test table'),
          source: source,
          rowsPerPage: 2,
          availableRowsPerPage: const <int>[
            2, 4, 8, 16,
          ],
720
          onRowsPerPageChanged: (int? rowsPerPage) {},
721 722 723 724 725 726
          onPageChanged: (int rowIndex) {},
          columns: const <DataColumn>[
            DataColumn(label: Text('Name')),
            DataColumn(label: Text('Calories'), numeric: true),
            DataColumn(label: Text('Generation')),
          ],
727 728
          horizontalMargin: customHorizontalMargin,
          columnSpacing: customColumnSpacing,
729 730 731 732 733 734 735 736 737
        ),
      ),
    ));

    // custom first column padding
    padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
    cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)');
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
738
      customHorizontalMargin,
739 740 741
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
742
      customColumnSpacing / 2,
743 744 745 746 747 748 749
    );

    // custom middle column padding
    padding = find.widgetWithText(Padding, '159').first;
    cellContent = find.widgetWithText(Align, '159');
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
750
      customColumnSpacing / 2,
751 752 753
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
754
      customColumnSpacing / 2,
755 756 757 758 759 760 761
    );

    // custom last column padding
    padding = find.widgetWithText(Padding, '0').first;
    cellContent = find.widgetWithText(Align, '0').first;
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
762
      customColumnSpacing / 2,
763 764 765
    );
    expect(
      tester.getRect(padding).right - tester.getRect(cellContent).right,
766
      customHorizontalMargin,
767 768
    );
  });
769 770 771 772 773

  testWidgets('PaginatedDataTable table fills Card width', (WidgetTester tester) async {
    final TestDataSource source = TestDataSource();

    // Note: 800 is wide enough to ensure that all of the columns fit in the
774 775
    // Card. The test makes sure that the DataTable is exactly as wide
    // as the Card, minus the Card's margin.
776 777 778
    const double originalWidth = 800;
    const double expandedWidth = 1600;
    const double height = 400;
779

780
    // By default, the margin of a Card is 4 in all directions, so
apeltop's avatar
apeltop committed
781
    // the size of the DataTable (inside the Card) is horizontally
782
    // reduced by 4 * 2; the left and right margins.
783
    const double cardMargin = 8;
784

785 786 787 788 789 790 791 792 793 794
    final Size originalSize = binding.renderView.size;

    Widget buildWidget() => MaterialApp(
      home: PaginatedDataTable(
        header: const Text('Test table'),
        source: source,
        rowsPerPage: 2,
        availableRowsPerPage: const <int>[
          2, 4, 8, 16,
        ],
795
        onRowsPerPageChanged: (int? rowsPerPage) {},
796 797 798 799 800 801 802 803 804
        onPageChanged: (int rowIndex) {},
        columns: const <DataColumn>[
          DataColumn(label: Text('Name')),
          DataColumn(label: Text('Calories'), numeric: true),
          DataColumn(label: Text('Generation')),
        ],
      ),
    );

805
    await binding.setSurfaceSize(const Size(originalWidth, height));
806 807
    await tester.pumpWidget(buildWidget());

808 809
    double cardWidth = tester.renderObject<RenderBox>(find.byType(Card).first).size.width;

810 811 812
    // Widths should be equal before we resize...
    expect(
      tester.renderObject<RenderBox>(find.byType(DataTable).first).size.width,
813
      moreOrLessEquals(cardWidth - cardMargin),
814 815
    );

816
    await binding.setSurfaceSize(const Size(expandedWidth, height));
817 818
    await tester.pumpWidget(buildWidget());

819
    cardWidth = tester.renderObject<RenderBox>(find.byType(Card).first).size.width;
820 821 822 823

    // ... and should still be equal after the resize.
    expect(
      tester.renderObject<RenderBox>(find.byType(DataTable).first).size.width,
824
      moreOrLessEquals(cardWidth - cardMargin),
825 826 827
    );

    // Double check to ensure we actually resized the surface properly.
828
    expect(cardWidth, moreOrLessEquals(expandedWidth));
829 830 831 832

    // Reset the surface size.
    await binding.setSurfaceSize(originalSize);
  });
833 834 835 836 837 838 839

  testWidgets('PaginatedDataTable with optional column checkbox', (WidgetTester tester) async {
    await binding.setSurfaceSize(const Size(800, 800));

    Widget buildTable(bool checkbox) => MaterialApp(
      home: PaginatedDataTable(
        header: const Text('Test table'),
840
        source: TestDataSource(allowSelection: true),
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
        showCheckboxColumn: checkbox,
        columns: const <DataColumn>[
          DataColumn(label: Text('Name')),
          DataColumn(label: Text('Calories'), numeric: true),
          DataColumn(label: Text('Generation')),
        ],
      ),
    );

    await tester.pumpWidget(buildTable(true));
    expect(find.byType(Checkbox), findsNWidgets(11));

    await tester.pumpWidget(buildTable(false));
    expect(find.byType(Checkbox), findsNothing);
  });
856 857 858 859 860 861 862 863 864 865 866 867 868 869

  testWidgets('Table should not use decoration from DataTableTheme', (WidgetTester tester) async {
    final Size originalSize = binding.renderView.size;
    await binding.setSurfaceSize(const Size(800, 800));

    Widget buildTable() {
      return MaterialApp(
        theme: ThemeData.light().copyWith(
            dataTableTheme: const DataTableThemeData(
              decoration: BoxDecoration(color: Colors.white),
            ),
        ),
        home: PaginatedDataTable(
          header: const Text('Test table'),
870
          source: TestDataSource(allowSelection: true),
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
          columns: const <DataColumn>[
            DataColumn(label: Text('Name')),
            DataColumn(label: Text('Calories'), numeric: true),
            DataColumn(label: Text('Generation')),
          ],
        ),
      );
    }

    await tester.pumpWidget(buildTable());
    final Finder tableContainerFinder = find.ancestor(of: find.byType(Table), matching: find.byType(Container)).first;
    expect(tester.widget<Container>(tableContainerFinder).decoration, const BoxDecoration());

    // Reset the surface size.
    await binding.setSurfaceSize(originalSize);
  });
887 888

  testWidgets('PaginatedDataTable custom checkboxHorizontalMargin properly applied', (WidgetTester tester) async {
889 890
    const double customCheckboxHorizontalMargin = 15.0;
    const double customHorizontalMargin = 10.0;
891

892 893
    const double width = 400;
    const double height = 400;
894 895 896 897 898

    final Size originalSize = binding.renderView.size;

    // Ensure the containing Card is small enough that we don't expand too
    // much, resulting in our custom margin being ignored.
899
    await binding.setSurfaceSize(const Size(width, height));
900

901
    final TestDataSource source = TestDataSource(allowSelection: true);
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
    Finder cellContent;
    Finder checkbox;
    Finder padding;

    // CUSTOM VALUES
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: PaginatedDataTable(
          header: const Text('Test table'),
          source: source,
          rowsPerPage: 2,
          availableRowsPerPage: const <int>[
            2, 4,
          ],
          onRowsPerPageChanged: (int? rowsPerPage) {},
          onPageChanged: (int rowIndex) {},
          onSelectAll: (bool? value) {},
          columns: const <DataColumn>[
            DataColumn(label: Text('Name')),
            DataColumn(label: Text('Calories'), numeric: true),
            DataColumn(label: Text('Generation')),
          ],
924 925
          horizontalMargin: customHorizontalMargin,
          checkboxHorizontalMargin: customCheckboxHorizontalMargin,
926 927 928 929 930 931 932 933 934
        ),
      ),
    ));

    // Custom checkbox padding.
    checkbox = find.byType(Checkbox).first;
    padding = find.ancestor(of: checkbox, matching: find.byType(Padding)).first;
    expect(
      tester.getRect(checkbox).left - tester.getRect(padding).left,
935
      customCheckboxHorizontalMargin,
936 937 938
    );
    expect(
      tester.getRect(padding).right - tester.getRect(checkbox).right,
939
      customCheckboxHorizontalMargin,
940 941 942 943 944 945 946
    );

    // Custom first column padding.
    padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
    cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)'); // DataTable wraps its DataCells in an Align widget.
    expect(
      tester.getRect(cellContent).left - tester.getRect(padding).left,
947
      customHorizontalMargin,
948 949 950 951 952
    );

    // Reset the surface size.
    await binding.setSurfaceSize(originalSize);
  });
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991

  testWidgets('Items selected text uses secondary color', (WidgetTester tester) async {
    const Color selectedTextColor = Color(0xff00ddff);
    final ColorScheme colors = const ColorScheme.light().copyWith(secondary: selectedTextColor);
    final ThemeData theme = ThemeData.from(colorScheme: colors);

    Widget buildTable() {
      return MaterialApp(
        theme: theme,
        home: PaginatedDataTable(
          header: const Text('Test table'),
          source: TestDataSource(allowSelection: true),
          columns: const <DataColumn>[
            DataColumn(label: Text('Name')),
            DataColumn(label: Text('Calories'), numeric: true),
            DataColumn(label: Text('Generation')),
          ],
        ),
      );
    }

    await binding.setSurfaceSize(const Size(800, 800));
    await tester.pumpWidget(buildTable());
    expect(find.text('Test table'), findsOneWidget);

    // Select a row with yogurt
    await tester.tap(find.text('Frozen yogurt (0)'));
    await tester.pumpAndSettle();

    // The header should be replace with a selected text item
    expect(find.text('Test table'), findsNothing);
    expect(find.text('1 item selected'), findsOneWidget);

    // The color of the selected text item should be the colorScheme.secondary
    final TextStyle selectedTextStyle = tester.renderObject<RenderParagraph>(find.text('1 item selected')).text.style!;
    expect(selectedTextStyle.color, equals(selectedTextColor));

    await binding.setSurfaceSize(null);
  });
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

  testWidgets('PaginatedDataTable arrowHeadColor set properly', (WidgetTester tester) async {
    await binding.setSurfaceSize(const Size(800, 800));
    const Color arrowHeadColor = Color(0xFFE53935);

    await tester.pumpWidget(
      MaterialApp(
        home: PaginatedDataTable(
          arrowHeadColor: arrowHeadColor,
          showFirstLastButtons: true,
          header: const Text('Test table'),
          source: TestDataSource(),
          columns: const <DataColumn>[
            DataColumn(label: Text('Name')),
            DataColumn(label: Text('Calories'), numeric: true),
            DataColumn(label: Text('Generation')),
          ],
        ),
      )
    );

    final Iterable<Icon> icons = tester.widgetList(find.byType(Icon));

    expect(icons.elementAt(0).color, arrowHeadColor);
    expect(icons.elementAt(1).color, arrowHeadColor);
    expect(icons.elementAt(2).color, arrowHeadColor);
    expect(icons.elementAt(3).color, arrowHeadColor);
  });
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

  testWidgets('OverflowBar header left alignment', (WidgetTester tester) async {
    // Test an old special case that tried to align the first child of a ButtonBar
    // and the left edge of a Text header widget. Still possible with OverflowBar
    // albeit without any special case in the implementation's build method.
    Widget buildFrame(Widget header) {
      return MaterialApp(
        home: PaginatedDataTable(
          header: header,
          rowsPerPage: 2,
          source: TestDataSource(),
          columns: const <DataColumn>[
            DataColumn(label: Text('Name')),
            DataColumn(label: Text('Calories'), numeric: true),
            DataColumn(label: Text('Generation')),
          ],
        ),
      );
    }

    await tester.pumpWidget(buildFrame(const Text('HEADER')));
    final double headerX = tester.getTopLeft(find.text('HEADER')).dx;
    final Widget overflowBar = OverflowBar(
      children: <Widget>[ElevatedButton(onPressed: () {}, child: const Text('BUTTON'))],
    );
    await tester.pumpWidget(buildFrame(overflowBar));
    expect(headerX, tester.getTopLeft(find.byType(ElevatedButton)).dx);
  });
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128

  testWidgets('PaginatedDataTable can be scrolled using ScrollController', (WidgetTester tester) async {
    final TestDataSource source = TestDataSource();
    final ScrollController scrollController = ScrollController();

    Widget buildTable(TestDataSource source) {
      return Align(
        alignment: Alignment.topLeft,
        child: SizedBox(
          width: 100,
          child: PaginatedDataTable(
            controller: scrollController,
            header: const Text('Test table'),
            source: source,
            rowsPerPage: 2,
            columns: const <DataColumn>[
              DataColumn(
                label: Text('Name'),
                tooltip: 'Name',
              ),
              DataColumn(
                label: Text('Calories'),
                tooltip: 'Calories',
                numeric: true,
              ),
              DataColumn(
                label: Text('Generation'),
                tooltip: 'Generation',
              ),
            ],
          ),
        ),
      );
    }

    await tester.pumpWidget(MaterialApp(
      home: buildTable(source),
    ));

    // DataTable uses provided ScrollController
    final Scrollable bodyScrollView = tester.widget(find.byType(Scrollable).first);
    expect(bodyScrollView.controller, scrollController);

    expect(scrollController.offset, 0.0);
    scrollController.jumpTo(50.0);
    await tester.pumpAndSettle();

    expect(scrollController.offset, 50.0);
  });

  testWidgets('PaginatedDataTable uses PrimaryScrollController when primary ', (WidgetTester tester) async {
    final ScrollController primaryScrollController = ScrollController();
    final TestDataSource source = TestDataSource();

    await tester.pumpWidget(
      MaterialApp(
        home: PrimaryScrollController(
          controller: primaryScrollController,
          child: PaginatedDataTable(
            primary: true,
            header: const Text('Test table'),
            source: source,
            rowsPerPage: 2,
            columns: const <DataColumn>[
              DataColumn(label: Text('Name')),
              DataColumn(label: Text('Calories'), numeric: true),
              DataColumn(label: Text('Generation')),
            ],
          ),
        ),
      )
    );

    // DataTable uses primaryScrollController
    final Scrollable bodyScrollView = tester.widget(find.byType(Scrollable).first);
    expect(bodyScrollView.controller, primaryScrollController);

    // Footer does not use primaryScrollController
    final Scrollable footerScrollView = tester.widget(find.byType(Scrollable).last);
    expect(footerScrollView.controller, null);
  });
1129
}