1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
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
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
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
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
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
// Copyright 2014 The Flutter Authors. All rights reserved.
// 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/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'checkbox.dart';
import 'constants.dart';
import 'data_table_theme.dart';
import 'debug.dart';
import 'divider.dart';
import 'dropdown.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'material.dart';
import 'material_state.dart';
import 'theme.dart';
import 'tooltip.dart';
// Examples can assume:
// late BuildContext context;
// late List<DataColumn> _columns;
// late List<DataRow> _rows;
/// Signature for [DataColumn.onSort] callback.
typedef DataColumnSortCallback = void Function(int columnIndex, bool ascending);
/// Column configuration for a [DataTable].
///
/// One column configuration must be provided for each column to
/// display in the table. The list of [DataColumn] objects is passed
/// as the `columns` argument to the [DataTable.new] constructor.
@immutable
class DataColumn {
/// Creates the configuration for a column of a [DataTable].
///
/// The [label] argument must not be null.
const DataColumn({
required this.label,
this.tooltip,
this.numeric = false,
this.onSort,
}) : assert(label != null);
/// The column heading.
///
/// Typically, this will be a [Text] widget. It could also be an
/// [Icon] (typically using size 18), or a [Row] with an icon and
/// some text.
///
/// The [label] is placed within a [Row] along with the
/// sort indicator (if applicable). By default, [label] only occupy minimal
/// space. It is recommended to place the label content in an [Expanded] or
/// [Flexible] as [label] to control how the content flexes. Otherwise,
/// an exception will occur when the available space is insufficient.
///
/// By default, [DefaultTextStyle.softWrap] of this subtree will be set to false.
/// Use [DefaultTextStyle.merge] to override it if needed.
///
/// The label should not include the sort indicator.
final Widget label;
/// The column heading's tooltip.
///
/// This is a longer description of the column heading, for cases
/// where the heading might have been abbreviated to keep the column
/// width to a reasonable size.
final String? tooltip;
/// Whether this column represents numeric data or not.
///
/// The contents of cells of columns containing numeric data are
/// right-aligned.
final bool numeric;
/// Called when the user asks to sort the table using this column.
///
/// If null, the column will not be considered sortable.
///
/// See [DataTable.sortColumnIndex] and [DataTable.sortAscending].
final DataColumnSortCallback? onSort;
bool get _debugInteractive => onSort != null;
}
/// Row configuration and cell data for a [DataTable].
///
/// One row configuration must be provided for each row to
/// display in the table. The list of [DataRow] objects is passed
/// as the `rows` argument to the [DataTable.new] constructor.
///
/// The data for this row of the table is provided in the [cells]
/// property of the [DataRow] object.
@immutable
class DataRow {
/// Creates the configuration for a row of a [DataTable].
///
/// The [cells] argument must not be null.
const DataRow({
this.key,
this.selected = false,
this.onSelectChanged,
this.onLongPress,
this.color,
required this.cells,
}) : assert(cells != null);
/// Creates the configuration for a row of a [DataTable], deriving
/// the key from a row index.
///
/// The [cells] argument must not be null.
DataRow.byIndex({
int? index,
this.selected = false,
this.onSelectChanged,
this.onLongPress,
this.color,
required this.cells,
}) : assert(cells != null),
key = ValueKey<int?>(index);
/// A [Key] that uniquely identifies this row. This is used to
/// ensure that if a row is added or removed, any stateful widgets
/// related to this row (e.g. an in-progress checkbox animation)
/// remain on the right row visually.
///
/// If the table never changes once created, no key is necessary.
final LocalKey? key;
/// Called when the user selects or unselects a selectable row.
///
/// If this is not null, then the row is selectable. The current
/// selection state of the row is given by [selected].
///
/// If any row is selectable, then the table's heading row will have
/// a checkbox that can be checked to select all selectable rows
/// (and which is checked if all the rows are selected), and each
/// subsequent row will have a checkbox to toggle just that row.
///
/// A row whose [onSelectChanged] callback is null is ignored for
/// the purposes of determining the state of the "all" checkbox,
/// and its checkbox is disabled.
///
/// If a [DataCell] in the row has its [DataCell.onTap] callback defined,
/// that callback behavior overrides the gesture behavior of the row for
/// that particular cell.
final ValueChanged<bool?>? onSelectChanged;
/// Called if the row is long-pressed.
///
/// If a [DataCell] in the row has its [DataCell.onTap], [DataCell.onDoubleTap],
/// [DataCell.onLongPress], [DataCell.onTapCancel] or [DataCell.onTapDown] callback defined,
/// that callback behavior overrides the gesture behavior of the row for
/// that particular cell.
final GestureLongPressCallback? onLongPress;
/// Whether the row is selected.
///
/// If [onSelectChanged] is non-null for any row in the table, then
/// a checkbox is shown at the start of each row. If the row is
/// selected (true), the checkbox will be checked and the row will
/// be highlighted.
///
/// Otherwise, the checkbox, if present, will not be checked.
final bool selected;
/// The data for this row.
///
/// There must be exactly as many cells as there are columns in the
/// table.
final List<DataCell> cells;
/// The color for the row.
///
/// By default, the color is transparent unless selected. Selected rows has
/// a grey translucent color.
///
/// The effective color can depend on the [MaterialState] state, if the
/// row is selected, pressed, hovered, focused, disabled or enabled. The
/// color is painted as an overlay to the row. To make sure that the row's
/// [InkWell] is visible (when pressed, hovered and focused), it is
/// recommended to use a translucent color.
///
/// ```dart
/// DataRow(
/// color: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
/// if (states.contains(MaterialState.selected)) {
/// return Theme.of(context).colorScheme.primary.withOpacity(0.08);
/// }
/// return null; // Use the default value.
/// }),
/// cells: const <DataCell>[
/// // ...
/// ],
/// )
/// ```
///
/// See also:
///
/// * The Material Design specification for overlay colors and how they
/// match a component's state:
/// <https://material.io/design/interaction/states.html#anatomy>.
final MaterialStateProperty<Color?>? color;
bool get _debugInteractive => onSelectChanged != null || cells.any((DataCell cell) => cell._debugInteractive);
}
/// The data for a cell of a [DataTable].
///
/// One list of [DataCell] objects must be provided for each [DataRow]
/// in the [DataTable], in the new [DataRow] constructor's `cells`
/// argument.
@immutable
class DataCell {
/// Creates an object to hold the data for a cell in a [DataTable].
///
/// The first argument is the widget to show for the cell, typically
/// a [Text] or [DropdownButton] widget; this becomes the [child]
/// property and must not be null.
///
/// If the cell has no data, then a [Text] widget with placeholder
/// text should be provided instead, and then the [placeholder]
/// argument should be set to true.
const DataCell(
this.child, {
this.placeholder = false,
this.showEditIcon = false,
this.onTap,
this.onLongPress,
this.onTapDown,
this.onDoubleTap,
this.onTapCancel,
}) : assert(child != null);
/// A cell that has no content and has zero width and height.
static const DataCell empty = DataCell(SizedBox.shrink());
/// The data for the row.
///
/// Typically a [Text] widget or a [DropdownButton] widget.
///
/// If the cell has no data, then a [Text] widget with placeholder
/// text should be provided instead, and [placeholder] should be set
/// to true.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// Whether the [child] is actually a placeholder.
///
/// If this is true, the default text style for the cell is changed
/// to be appropriate for placeholder text.
final bool placeholder;
/// Whether to show an edit icon at the end of the cell.
///
/// This does not make the cell actually editable; the caller must
/// implement editing behavior if desired (initiated from the
/// [onTap] callback).
///
/// If this is set, [onTap] should also be set, otherwise tapping
/// the icon will have no effect.
final bool showEditIcon;
/// Called if the cell is tapped.
///
/// If non-null, tapping the cell will call this callback. If
/// null (including [onDoubleTap], [onLongPress], [onTapCancel] and [onTapDown]),
/// tapping the cell will attempt to select the row (if
/// [DataRow.onSelectChanged] is provided).
final GestureTapCallback? onTap;
/// Called when the cell is double tapped.
///
/// If non-null, tapping the cell will call this callback. If
/// null (including [onTap], [onLongPress], [onTapCancel] and [onTapDown]),
/// tapping the cell will attempt to select the row (if
/// [DataRow.onSelectChanged] is provided).
final GestureTapCallback? onDoubleTap;
/// Called if the cell is long-pressed.
///
/// If non-null, tapping the cell will invoke this callback. If
/// null (including [onDoubleTap], [onTap], [onTapCancel] and [onTapDown]),
/// tapping the cell will attempt to select the row (if
/// [DataRow.onSelectChanged] is provided).
final GestureLongPressCallback? onLongPress;
/// Called if the cell is tapped down.
///
/// If non-null, tapping the cell will call this callback. If
/// null (including [onTap] [onDoubleTap], [onLongPress] and [onTapCancel]),
/// tapping the cell will attempt to select the row (if
/// [DataRow.onSelectChanged] is provided).
final GestureTapDownCallback? onTapDown;
/// Called if the user cancels a tap was started on cell.
///
/// If non-null, canceling the tap gesture will invoke this callback.
/// If null (including [onTap], [onDoubleTap] and [onLongPress]),
/// tapping the cell will attempt to select the
/// row (if [DataRow.onSelectChanged] is provided).
final GestureTapCancelCallback? onTapCancel;
bool get _debugInteractive => onTap != null ||
onDoubleTap != null ||
onLongPress != null ||
onTapDown != null ||
onTapCancel != null;
}
/// A Material Design data table.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=ktTajqbhIcY}
///
/// Displaying data in a table is expensive, because to lay out the
/// table all the data must be measured twice, once to negotiate the
/// dimensions to use for each column, and once to actually lay out
/// the table given the results of the negotiation.
///
/// For this reason, if you have a lot of data (say, more than a dozen
/// rows with a dozen columns, though the precise limits depend on the
/// target device), it is suggested that you use a
/// [PaginatedDataTable] which automatically splits the data into
/// multiple pages.
///
/// {@tool dartpad}
/// This sample shows how to display a [DataTable] with three columns: name, age, and
/// role. The columns are defined by three [DataColumn] objects. The table
/// contains three rows of data for three example users, the data for which
/// is defined by three [DataRow] objects.
///
/// 
///
/// ** See code in examples/api/lib/material/data_table/data_table.0.dart **
/// {@end-tool}
///
///
/// {@tool dartpad}
/// This sample shows how to display a [DataTable] with alternate colors per
/// row, and a custom color for when the row is selected.
///
/// ** See code in examples/api/lib/material/data_table/data_table.1.dart **
/// {@end-tool}
///
/// [DataTable] can be sorted on the basis of any column in [columns] in
/// ascending or descending order. If [sortColumnIndex] is non-null, then the
/// table will be sorted by the values in the specified column. The boolean
/// [sortAscending] flag controls the sort order.
///
/// See also:
///
/// * [DataColumn], which describes a column in the data table.
/// * [DataRow], which contains the data for a row in the data table.
/// * [DataCell], which contains the data for a single cell in the data table.
/// * [PaginatedDataTable], which shows part of the data in a data table and
/// provides controls for paging through the remainder of the data.
/// * <https://material.io/design/components/data-tables.html>
class DataTable extends StatelessWidget {
/// Creates a widget describing a data table.
///
/// 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 must not be null.
///
/// The [rows] argument must be a list of as many [DataRow] objects
/// as the table is to have rows, ignoring the leading heading row
/// that contains the column headings (derived from the [columns]
/// argument). There may be zero rows, but the rows argument must
/// not be null.
///
/// Each [DataRow] object in [rows] must have as many [DataCell]
/// objects in the [DataRow.cells] list as the table has columns.
///
/// 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.
DataTable({
super.key,
required this.columns,
this.sortColumnIndex,
this.sortAscending = true,
this.onSelectAll,
this.decoration,
this.dataRowColor,
this.dataRowHeight,
this.dataTextStyle,
this.headingRowColor,
this.headingRowHeight,
this.headingTextStyle,
this.horizontalMargin,
this.columnSpacing,
this.showCheckboxColumn = true,
this.showBottomBorder = false,
this.dividerThickness,
required this.rows,
this.checkboxHorizontalMargin,
this.border,
this.clipBehavior = Clip.none,
}) : assert(columns != null),
assert(columns.isNotEmpty),
assert(sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length)),
assert(sortAscending != null),
assert(showCheckboxColumn != null),
assert(rows != null),
assert(!rows.any((DataRow row) => row.cells.length != columns.length)),
assert(dividerThickness == null || dividerThickness >= 0),
assert(clipBehavior != null),
_onlyTextColumn = _initOnlyTextColumn(columns);
/// The configuration and labels for the columns in the table.
final List<DataColumn> columns;
/// The current primary sort key's column.
///
/// If non-null, indicates that the indicated column is the column
/// by which the data is sorted. The number must correspond to the
/// index of the relevant column in [columns].
///
/// Setting this will cause the relevant column to have a sort
/// indicator displayed.
///
/// When this is null, it implies that the table's sort order does
/// not correspond to any of the columns.
final int? sortColumnIndex;
/// Whether the column mentioned in [sortColumnIndex], if any, is sorted
/// in ascending order.
///
/// If true, the order is ascending (meaning the rows with the
/// smallest values for the current sort column are first in the
/// table).
///
/// If false, the order is descending (meaning the rows with the
/// smallest values for the current sort column are last in the
/// table).
final bool sortAscending;
/// Invoked when the user selects or unselects every row, using the
/// checkbox in the heading row.
///
/// If this is null, then the [DataRow.onSelectChanged] callback of
/// every row in the table is invoked appropriately instead.
///
/// To control whether a particular row is selectable or not, see
/// [DataRow.onSelectChanged]. This callback is only relevant if any
/// row is selectable.
final ValueSetter<bool?>? onSelectAll;
/// {@template flutter.material.dataTable.decoration}
/// The background and border decoration for the table.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.decoration] is used. By default there is no
/// decoration.
final Decoration? decoration;
/// {@template flutter.material.dataTable.dataRowColor}
/// The background color for the data rows.
///
/// The effective background color can be made to depend on the
/// [MaterialState] state, i.e. if the row is selected, pressed, hovered,
/// focused, disabled or enabled. The color is painted as an overlay to the
/// row. To make sure that the row's [InkWell] is visible (when pressed,
/// hovered and focused), it is recommended to use a translucent background
/// color.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.dataRowColor] is used. By default, the
/// background color is transparent unless selected. Selected rows have a grey
/// translucent color. To set a different color for individual rows, see
/// [DataRow.color].
///
/// {@template flutter.material.DataTable.dataRowColor}
/// ```dart
/// DataTable(
/// dataRowColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
/// if (states.contains(MaterialState.selected)) {
/// return Theme.of(context).colorScheme.primary.withOpacity(0.08);
/// }
/// return null; // Use the default value.
/// }),
/// columns: _columns,
/// rows: _rows,
/// )
/// ```
///
/// See also:
///
/// * The Material Design specification for overlay colors and how they
/// match a component's state:
/// <https://material.io/design/interaction/states.html#anatomy>.
/// {@endtemplate}
final MaterialStateProperty<Color?>? dataRowColor;
/// {@template flutter.material.dataTable.dataRowHeight}
/// The height of each row (excluding the row that contains column headings).
/// {@endtemplate}
///
/// If null, [DataTableThemeData.dataRowHeight] is used. This value defaults
/// to [kMinInteractiveDimension] to adhere to the Material Design
/// specifications.
final double? dataRowHeight;
/// {@template flutter.material.dataTable.dataTextStyle}
/// The text style for data rows.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.dataTextStyle] is used. By default, the text
/// style is [TextTheme.bodyMedium].
final TextStyle? dataTextStyle;
/// {@template flutter.material.dataTable.headingRowColor}
/// The background color for the heading row.
///
/// The effective background color can be made to depend on the
/// [MaterialState] state, i.e. if the row is pressed, hovered, focused when
/// sorted. The color is painted as an overlay to the row. To make sure that
/// the row's [InkWell] is visible (when pressed, hovered and focused), it is
/// recommended to use a translucent color.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.headingRowColor] is used.
///
/// {@template flutter.material.DataTable.headingRowColor}
/// ```dart
/// DataTable(
/// columns: _columns,
/// rows: _rows,
/// headingRowColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
/// if (states.contains(MaterialState.hovered)) {
/// return Theme.of(context).colorScheme.primary.withOpacity(0.08);
/// }
/// return null; // Use the default value.
/// }),
/// )
/// ```
///
/// See also:
///
/// * The Material Design specification for overlay colors and how they
/// match a component's state:
/// <https://material.io/design/interaction/states.html#anatomy>.
/// {@endtemplate}
final MaterialStateProperty<Color?>? headingRowColor;
/// {@template flutter.material.dataTable.headingRowHeight}
/// The height of the heading row.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.headingRowHeight] is used. This value
/// defaults to 56.0 to adhere to the Material Design specifications.
final double? headingRowHeight;
/// {@template flutter.material.dataTable.headingTextStyle}
/// The text style for the heading row.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.headingTextStyle] is used. By default, the
/// text style is [TextTheme.titleSmall].
final TextStyle? headingTextStyle;
/// {@template flutter.material.dataTable.horizontalMargin}
/// The horizontal margin between the edges of the table and the content
/// in the first and last cells of each row.
///
/// When a checkbox is displayed, it is also the margin between the checkbox
/// the content in the first data column.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.horizontalMargin] is used. This value
/// defaults to 24.0 to adhere to the Material Design specifications.
///
/// If [checkboxHorizontalMargin] is null, then [horizontalMargin] is also the
/// margin between the edge of the table and the checkbox, as well as the
/// margin between the checkbox and the content in the first data column.
final double? horizontalMargin;
/// {@template flutter.material.dataTable.columnSpacing}
/// The horizontal margin between the contents of each data column.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.columnSpacing] is used. This value defaults
/// to 56.0 to adhere to the Material Design specifications.
final double? columnSpacing;
/// {@template flutter.material.dataTable.showCheckboxColumn}
/// Whether the widget should display checkboxes for selectable rows.
///
/// If true, a [Checkbox] will be placed at the beginning of each row that is
/// selectable. However, if [DataRow.onSelectChanged] is not set for any row,
/// checkboxes will not be placed, even if this value is true.
///
/// If false, all rows will not display a [Checkbox].
/// {@endtemplate}
final bool showCheckboxColumn;
/// The data to show in each row (excluding the row that contains
/// the column headings).
///
/// Must be non-null, but may be empty.
final List<DataRow> rows;
/// {@template flutter.material.dataTable.dividerThickness}
/// The width of the divider that appears between [TableRow]s.
///
/// Must be greater than or equal to zero.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.dividerThickness] is used. This value
/// defaults to 1.0.
final double? dividerThickness;
/// Whether a border at the bottom of the table is displayed.
///
/// By default, a border is not shown at the bottom to allow for a border
/// around the table defined by [decoration].
final bool showBottomBorder;
/// {@template flutter.material.dataTable.checkboxHorizontalMargin}
/// Horizontal margin around the checkbox, if it is displayed.
/// {@endtemplate}
///
/// If null, [DataTableThemeData.checkboxHorizontalMargin] is used. If that is
/// also null, then [horizontalMargin] is used as the margin between the edge
/// of the table and the checkbox, as well as the margin between the checkbox
/// and the content in the first data column. This value defaults to 24.0.
final double? checkboxHorizontalMargin;
/// The style to use when painting the boundary and interior divisions of the table.
final TableBorder? border;
/// {@macro flutter.material.Material.clipBehavior}
///
/// This can be used to clip the content within the border of the [DataTable].
///
/// Defaults to [Clip.none], and must not be null.
final Clip clipBehavior;
// Set by the constructor to the index of the only Column that is
// non-numeric, if there is exactly one, otherwise null.
final int? _onlyTextColumn;
static int? _initOnlyTextColumn(List<DataColumn> columns) {
int? result;
for (int index = 0; index < columns.length; index += 1) {
final DataColumn column = columns[index];
if (!column.numeric) {
if (result != null) {
return null;
}
result = index;
}
}
return result;
}
bool get _debugInteractive {
return columns.any((DataColumn column) => column._debugInteractive)
|| rows.any((DataRow row) => row._debugInteractive);
}
static final LocalKey _headingRowKey = UniqueKey();
void _handleSelectAll(bool? checked, bool someChecked) {
// If some checkboxes are checked, all checkboxes are selected. Otherwise,
// use the new checked value but default to false if it's null.
final bool effectiveChecked = someChecked || (checked ?? false);
if (onSelectAll != null) {
onSelectAll!(effectiveChecked);
} else {
for (final DataRow row in rows) {
if (row.onSelectChanged != null && row.selected != effectiveChecked) {
row.onSelectChanged!(effectiveChecked);
}
}
}
}
/// The default height of the heading row.
static const double _headingRowHeight = 56.0;
/// The default horizontal margin between the edges of the table and the content
/// in the first and last cells of each row.
static const double _horizontalMargin = 24.0;
/// The default horizontal margin between the contents of each data column.
static const double _columnSpacing = 56.0;
/// The default padding between the heading content and sort arrow.
static const double _sortArrowPadding = 2.0;
/// The default divider thickness.
static const double _dividerThickness = 1.0;
static const Duration _sortArrowAnimationDuration = Duration(milliseconds: 150);
Widget _buildCheckbox({
required BuildContext context,
required bool? checked,
required VoidCallback? onRowTap,
required ValueChanged<bool?>? onCheckboxChanged,
required MaterialStateProperty<Color?>? overlayColor,
required bool tristate,
}) {
final ThemeData themeData = Theme.of(context);
final double effectiveHorizontalMargin = horizontalMargin
?? themeData.dataTableTheme.horizontalMargin
?? _horizontalMargin;
final double effectiveCheckboxHorizontalMarginStart = checkboxHorizontalMargin
?? themeData.dataTableTheme.checkboxHorizontalMargin
?? effectiveHorizontalMargin;
final double effectiveCheckboxHorizontalMarginEnd = checkboxHorizontalMargin
?? themeData.dataTableTheme.checkboxHorizontalMargin
?? effectiveHorizontalMargin / 2.0;
Widget contents = Semantics(
container: true,
child: Padding(
padding: EdgeInsetsDirectional.only(
start: effectiveCheckboxHorizontalMarginStart,
end: effectiveCheckboxHorizontalMarginEnd,
),
child: Center(
child: Checkbox(
value: checked,
onChanged: onCheckboxChanged,
tristate: tristate,
),
),
),
);
if (onRowTap != null) {
contents = TableRowInkWell(
onTap: onRowTap,
overlayColor: overlayColor,
child: contents,
);
}
return TableCell(
verticalAlignment: TableCellVerticalAlignment.fill,
child: contents,
);
}
Widget _buildHeadingCell({
required BuildContext context,
required EdgeInsetsGeometry padding,
required Widget label,
required String? tooltip,
required bool numeric,
required VoidCallback? onSort,
required bool sorted,
required bool ascending,
required MaterialStateProperty<Color?>? overlayColor,
}) {
final ThemeData themeData = Theme.of(context);
final DataTableThemeData dataTableTheme = DataTableTheme.of(context);
label = Row(
textDirection: numeric ? TextDirection.rtl : null,
children: <Widget>[
label,
if (onSort != null)
...<Widget>[
_SortArrow(
visible: sorted,
up: sorted ? ascending : null,
duration: _sortArrowAnimationDuration,
),
const SizedBox(width: _sortArrowPadding),
],
],
);
final TextStyle effectiveHeadingTextStyle = headingTextStyle
?? dataTableTheme.headingTextStyle
?? themeData.dataTableTheme.headingTextStyle
?? themeData.textTheme.titleSmall!;
final double effectiveHeadingRowHeight = headingRowHeight
?? dataTableTheme.headingRowHeight
?? themeData.dataTableTheme.headingRowHeight
?? _headingRowHeight;
label = Container(
padding: padding,
height: effectiveHeadingRowHeight,
alignment: numeric ? Alignment.centerRight : AlignmentDirectional.centerStart,
child: AnimatedDefaultTextStyle(
style: effectiveHeadingTextStyle,
softWrap: false,
duration: _sortArrowAnimationDuration,
child: label,
),
);
if (tooltip != null) {
label = Tooltip(
message: tooltip,
child: label,
);
}
// TODO(dkwingsmt): Only wrap Inkwell if onSort != null. Blocked by
// https://github.com/flutter/flutter/issues/51152
label = InkWell(
onTap: onSort,
overlayColor: overlayColor,
child: label,
);
return label;
}
Widget _buildDataCell({
required BuildContext context,
required EdgeInsetsGeometry padding,
required Widget label,
required bool numeric,
required bool placeholder,
required bool showEditIcon,
required GestureTapCallback? onTap,
required VoidCallback? onSelectChanged,
required GestureTapCallback? onDoubleTap,
required GestureLongPressCallback? onLongPress,
required GestureTapDownCallback? onTapDown,
required GestureTapCancelCallback? onTapCancel,
required MaterialStateProperty<Color?>? overlayColor,
required GestureLongPressCallback? onRowLongPress,
}) {
final ThemeData themeData = Theme.of(context);
final DataTableThemeData dataTableTheme = DataTableTheme.of(context);
if (showEditIcon) {
const Widget icon = Icon(Icons.edit, size: 18.0);
label = Expanded(child: label);
label = Row(
textDirection: numeric ? TextDirection.rtl : null,
children: <Widget>[ label, icon ],
);
}
final TextStyle effectiveDataTextStyle = dataTextStyle
?? dataTableTheme.dataTextStyle
?? themeData.dataTableTheme.dataTextStyle
?? themeData.textTheme.bodyMedium!;
final double effectiveDataRowHeight = dataRowHeight
?? dataTableTheme.dataRowHeight
?? themeData.dataTableTheme.dataRowHeight
?? kMinInteractiveDimension;
label = Container(
padding: padding,
height: effectiveDataRowHeight,
alignment: numeric ? Alignment.centerRight : AlignmentDirectional.centerStart,
child: DefaultTextStyle(
style: effectiveDataTextStyle.copyWith(
color: placeholder ? effectiveDataTextStyle.color!.withOpacity(0.6) : null,
),
child: DropdownButtonHideUnderline(child: label),
),
);
if (onTap != null ||
onDoubleTap != null ||
onLongPress != null ||
onTapDown != null ||
onTapCancel != null) {
label = InkWell(
onTap: onTap,
onDoubleTap: onDoubleTap,
onLongPress: onLongPress,
onTapCancel: onTapCancel,
onTapDown: onTapDown,
overlayColor: overlayColor,
child: label,
);
} else if (onSelectChanged != null || onRowLongPress != null) {
label = TableRowInkWell(
onTap: onSelectChanged,
onLongPress: onRowLongPress,
overlayColor: overlayColor,
child: label,
);
}
return label;
}
@override
Widget build(BuildContext context) {
assert(!_debugInteractive || debugCheckHasMaterial(context));
final ThemeData theme = Theme.of(context);
final DataTableThemeData dataTableTheme = DataTableTheme.of(context);
final MaterialStateProperty<Color?>? effectiveHeadingRowColor = headingRowColor
?? dataTableTheme.headingRowColor
?? theme.dataTableTheme.headingRowColor;
final MaterialStateProperty<Color?>? effectiveDataRowColor = dataRowColor
?? dataTableTheme.dataRowColor
?? theme.dataTableTheme.dataRowColor;
final MaterialStateProperty<Color?> defaultRowColor = MaterialStateProperty.resolveWith(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return theme.colorScheme.primary.withOpacity(0.08);
}
return null;
},
);
final bool anyRowSelectable = rows.any((DataRow row) => row.onSelectChanged != null);
final bool displayCheckboxColumn = showCheckboxColumn && anyRowSelectable;
final Iterable<DataRow> rowsWithCheckbox = displayCheckboxColumn ?
rows.where((DataRow row) => row.onSelectChanged != null) : <DataRow>[];
final Iterable<DataRow> rowsChecked = rowsWithCheckbox.where((DataRow row) => row.selected);
final bool allChecked = displayCheckboxColumn && rowsChecked.length == rowsWithCheckbox.length;
final bool anyChecked = displayCheckboxColumn && rowsChecked.isNotEmpty;
final bool someChecked = anyChecked && !allChecked;
final double effectiveHorizontalMargin = horizontalMargin
?? dataTableTheme.horizontalMargin
?? theme.dataTableTheme.horizontalMargin
?? _horizontalMargin;
final double effectiveCheckboxHorizontalMarginStart = checkboxHorizontalMargin
?? dataTableTheme.checkboxHorizontalMargin
?? theme.dataTableTheme.checkboxHorizontalMargin
?? effectiveHorizontalMargin;
final double effectiveCheckboxHorizontalMarginEnd = checkboxHorizontalMargin
?? dataTableTheme.checkboxHorizontalMargin
?? theme.dataTableTheme.checkboxHorizontalMargin
?? effectiveHorizontalMargin / 2.0;
final double effectiveColumnSpacing = columnSpacing
?? dataTableTheme.columnSpacing
?? theme.dataTableTheme.columnSpacing
?? _columnSpacing;
final List<TableColumnWidth> tableColumns = List<TableColumnWidth>.filled(columns.length + (displayCheckboxColumn ? 1 : 0), const _NullTableColumnWidth());
final List<TableRow> tableRows = List<TableRow>.generate(
rows.length + 1, // the +1 is for the header row
(int index) {
final bool isSelected = index > 0 && rows[index - 1].selected;
final bool isDisabled = index > 0 && anyRowSelectable && rows[index - 1].onSelectChanged == null;
final Set<MaterialState> states = <MaterialState>{
if (isSelected)
MaterialState.selected,
if (isDisabled)
MaterialState.disabled,
};
final Color? resolvedDataRowColor = index > 0 ? (rows[index - 1].color ?? effectiveDataRowColor)?.resolve(states) : null;
final Color? resolvedHeadingRowColor = effectiveHeadingRowColor?.resolve(<MaterialState>{});
final Color? rowColor = index > 0 ? resolvedDataRowColor : resolvedHeadingRowColor;
final BorderSide borderSide = Divider.createBorderSide(
context,
width: dividerThickness
?? dataTableTheme.dividerThickness
?? theme.dataTableTheme.dividerThickness
?? _dividerThickness,
);
final Border? border = showBottomBorder
? Border(bottom: borderSide)
: index == 0 ? null : Border(top: borderSide);
return TableRow(
key: index == 0 ? _headingRowKey : rows[index - 1].key,
decoration: BoxDecoration(
border: border,
color: rowColor ?? defaultRowColor.resolve(states),
),
children: List<Widget>.filled(tableColumns.length, const _NullWidget()),
);
},
);
int rowIndex;
int displayColumnIndex = 0;
if (displayCheckboxColumn) {
tableColumns[0] = FixedColumnWidth(effectiveCheckboxHorizontalMarginStart + Checkbox.width + effectiveCheckboxHorizontalMarginEnd);
tableRows[0].children![0] = _buildCheckbox(
context: context,
checked: someChecked ? null : allChecked,
onRowTap: null,
onCheckboxChanged: (bool? checked) => _handleSelectAll(checked, someChecked),
overlayColor: null,
tristate: true,
);
rowIndex = 1;
for (final DataRow row in rows) {
tableRows[rowIndex].children![0] = _buildCheckbox(
context: context,
checked: row.selected,
onRowTap: row.onSelectChanged == null ? null : () => row.onSelectChanged?.call(!row.selected),
onCheckboxChanged: row.onSelectChanged,
overlayColor: row.color ?? effectiveDataRowColor,
tristate: false,
);
rowIndex += 1;
}
displayColumnIndex += 1;
}
for (int dataColumnIndex = 0; dataColumnIndex < columns.length; dataColumnIndex += 1) {
final DataColumn column = columns[dataColumnIndex];
final double paddingStart;
if (dataColumnIndex == 0 && displayCheckboxColumn && checkboxHorizontalMargin != null) {
paddingStart = effectiveHorizontalMargin;
} else if (dataColumnIndex == 0 && displayCheckboxColumn) {
paddingStart = effectiveHorizontalMargin / 2.0;
} else if (dataColumnIndex == 0 && !displayCheckboxColumn) {
paddingStart = effectiveHorizontalMargin;
} else {
paddingStart = effectiveColumnSpacing / 2.0;
}
final double paddingEnd;
if (dataColumnIndex == columns.length - 1) {
paddingEnd = effectiveHorizontalMargin;
} else {
paddingEnd = effectiveColumnSpacing / 2.0;
}
final EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(
start: paddingStart,
end: paddingEnd,
);
if (dataColumnIndex == _onlyTextColumn) {
tableColumns[displayColumnIndex] = const IntrinsicColumnWidth(flex: 1.0);
} else {
tableColumns[displayColumnIndex] = const IntrinsicColumnWidth();
}
tableRows[0].children![displayColumnIndex] = _buildHeadingCell(
context: context,
padding: padding,
label: column.label,
tooltip: column.tooltip,
numeric: column.numeric,
onSort: column.onSort != null ? () => column.onSort!(dataColumnIndex, sortColumnIndex != dataColumnIndex || !sortAscending) : null,
sorted: dataColumnIndex == sortColumnIndex,
ascending: sortAscending,
overlayColor: effectiveHeadingRowColor,
);
rowIndex = 1;
for (final DataRow row in rows) {
final DataCell cell = row.cells[dataColumnIndex];
tableRows[rowIndex].children![displayColumnIndex] = _buildDataCell(
context: context,
padding: padding,
label: cell.child,
numeric: column.numeric,
placeholder: cell.placeholder,
showEditIcon: cell.showEditIcon,
onTap: cell.onTap,
onDoubleTap: cell.onDoubleTap,
onLongPress: cell.onLongPress,
onTapCancel: cell.onTapCancel,
onTapDown: cell.onTapDown,
onSelectChanged: row.onSelectChanged == null ? null : () => row.onSelectChanged?.call(!row.selected),
overlayColor: row.color ?? effectiveDataRowColor,
onRowLongPress: row.onLongPress,
);
rowIndex += 1;
}
displayColumnIndex += 1;
}
return Container(
decoration: decoration ?? dataTableTheme.decoration ?? theme.dataTableTheme.decoration,
child: Material(
type: MaterialType.transparency,
borderRadius: border?.borderRadius,
clipBehavior: clipBehavior,
child: Table(
columnWidths: tableColumns.asMap(),
children: tableRows,
border: border,
),
),
);
}
}
/// A rectangular area of a Material that responds to touch but clips
/// its ink splashes to the current table row of the nearest table.
///
/// Must have an ancestor [Material] widget in which to cause ink
/// reactions and an ancestor [Table] widget to establish a row.
///
/// The [TableRowInkWell] must be in the same coordinate space (modulo
/// translations) as the [Table]. If it's rotated or scaled or
/// otherwise transformed, it will not be able to describe the
/// rectangle of the row in its own coordinate system as a [Rect], and
/// thus the splash will not occur. (In general, this is easy to
/// achieve: just put the [TableRowInkWell] as the direct child of the
/// [Table], and put the other contents of the cell inside it.)
///
/// See also:
///
/// * [DataTable], which makes use of [TableRowInkWell] when
/// [DataRow.onSelectChanged] is defined and [DataCell.onTap]
/// is not.
class TableRowInkWell extends InkResponse {
/// Creates an ink well for a table row.
const TableRowInkWell({
super.key,
super.child,
super.onTap,
super.onDoubleTap,
super.onLongPress,
super.onHighlightChanged,
super.overlayColor,
}) : super(
containedInkWell: true,
highlightShape: BoxShape.rectangle,
);
@override
RectCallback getRectCallback(RenderBox referenceBox) {
return () {
RenderObject cell = referenceBox;
AbstractNode? table = cell.parent;
final Matrix4 transform = Matrix4.identity();
while (table is RenderObject && table is! RenderTable) {
table.applyPaintTransform(cell, transform);
assert(table == cell.parent);
cell = table;
table = table.parent;
}
if (table is RenderTable) {
final TableCellParentData cellParentData = cell.parentData! as TableCellParentData;
assert(cellParentData.y != null);
final Rect rect = table.getRowBox(cellParentData.y!);
// The rect is in the table's coordinate space. We need to change it to the
// TableRowInkWell's coordinate space.
table.applyPaintTransform(cell, transform);
final Offset? offset = MatrixUtils.getAsTranslation(transform);
if (offset != null) {
return rect.shift(-offset);
}
}
return Rect.zero;
};
}
@override
bool debugCheckContext(BuildContext context) {
assert(debugCheckHasTable(context));
return super.debugCheckContext(context);
}
}
class _SortArrow extends StatefulWidget {
const _SortArrow({
required this.visible,
required this.up,
required this.duration,
});
final bool visible;
final bool? up;
final Duration duration;
@override
_SortArrowState createState() => _SortArrowState();
}
class _SortArrowState extends State<_SortArrow> with TickerProviderStateMixin {
late AnimationController _opacityController;
late Animation<double> _opacityAnimation;
late AnimationController _orientationController;
late Animation<double> _orientationAnimation;
double _orientationOffset = 0.0;
bool? _up;
static final Animatable<double> _turnTween = Tween<double>(begin: 0.0, end: math.pi)
.chain(CurveTween(curve: Curves.easeIn));
@override
void initState() {
super.initState();
_up = widget.up;
_opacityAnimation = CurvedAnimation(
parent: _opacityController = AnimationController(
duration: widget.duration,
vsync: this,
),
curve: Curves.fastOutSlowIn,
)
..addListener(_rebuild);
_opacityController.value = widget.visible ? 1.0 : 0.0;
_orientationController = AnimationController(
duration: widget.duration,
vsync: this,
);
_orientationAnimation = _orientationController.drive(_turnTween)
..addListener(_rebuild)
..addStatusListener(_resetOrientationAnimation);
if (widget.visible) {
_orientationOffset = widget.up! ? 0.0 : math.pi;
}
}
void _rebuild() {
setState(() {
// The animations changed, so we need to rebuild.
});
}
void _resetOrientationAnimation(AnimationStatus status) {
if (status == AnimationStatus.completed) {
assert(_orientationAnimation.value == math.pi);
_orientationOffset += math.pi;
_orientationController.value = 0.0; // TODO(ianh): This triggers a pointless rebuild.
}
}
@override
void didUpdateWidget(_SortArrow oldWidget) {
super.didUpdateWidget(oldWidget);
bool skipArrow = false;
final bool? newUp = widget.up ?? _up;
if (oldWidget.visible != widget.visible) {
if (widget.visible && (_opacityController.status == AnimationStatus.dismissed)) {
_orientationController.stop();
_orientationController.value = 0.0;
_orientationOffset = newUp! ? 0.0 : math.pi;
skipArrow = true;
}
if (widget.visible) {
_opacityController.forward();
} else {
_opacityController.reverse();
}
}
if ((_up != newUp) && !skipArrow) {
if (_orientationController.status == AnimationStatus.dismissed) {
_orientationController.forward();
} else {
_orientationController.reverse();
}
}
_up = newUp;
}
@override
void dispose() {
_opacityController.dispose();
_orientationController.dispose();
super.dispose();
}
static const double _arrowIconBaselineOffset = -1.5;
static const double _arrowIconSize = 16.0;
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: _opacityAnimation,
child: Transform(
transform: Matrix4.rotationZ(_orientationOffset + _orientationAnimation.value)
..setTranslationRaw(0.0, _arrowIconBaselineOffset, 0.0),
alignment: Alignment.center,
child: const Icon(
Icons.arrow_upward,
size: _arrowIconSize,
),
),
);
}
}
class _NullTableColumnWidth extends TableColumnWidth {
const _NullTableColumnWidth();
@override
double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) => throw UnimplementedError();
@override
double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) => throw UnimplementedError();
}
class _NullWidget extends Widget {
const _NullWidget();
@override
Element createElement() => throw UnimplementedError();
}