DataTable class

A data table that follows the Material 2 design specification.

Learn more about DataTable on the Flutter YouTube channel.

Performance considerations

Columns are sized automatically based on the table's contents. It's expensive to display large amounts of data with this widget, since it must be measured twice: once to negotiate each column's dimensions, and again when the table is laid out.

A SingleChildScrollView mounts and paints the entire child, even when only some of it is visible. For a table that effectively handles large amounts of data, here are some other options to consider:

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.

To see it in action, copy and run this code snippet on DartPad.

import 'package:material_ui/material_ui.dart';

/// Flutter code sample for [DataTable].

void main() => runApp(const DataTableExampleApp());

class DataTableExampleApp extends StatelessWidget {
  const DataTableExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('DataTable Sample')),
        body: const DataTableExample(),
      ),
    );
  }
}

class DataTableExample extends StatelessWidget {
  const DataTableExample({super.key});

  @override
  Widget build(BuildContext context) {
    return DataTable(
      columns: const <DataColumn>[
        DataColumn(
          label: Expanded(
            child: Text('Name', style: TextStyle(fontStyle: .italic)),
          ),
        ),
        DataColumn(
          label: Expanded(
            child: Text('Age', style: TextStyle(fontStyle: .italic)),
          ),
        ),
        DataColumn(
          label: Expanded(
            child: Text('Role', style: TextStyle(fontStyle: .italic)),
          ),
        ),
      ],
      rows: const <DataRow>[
        DataRow(
          cells: <DataCell>[
            DataCell(Text('Sarah')),
            DataCell(Text('19')),
            DataCell(Text('Student')),
          ],
        ),
        DataRow(
          cells: <DataCell>[
            DataCell(Text('Janine')),
            DataCell(Text('43')),
            DataCell(Text('Professor')),
          ],
        ),
        DataRow(
          cells: <DataCell>[
            DataCell(Text('William')),
            DataCell(Text('27')),
            DataCell(Text('Associate Professor')),
          ],
        ),
      ],
    );
  }
}

This sample shows how to display a DataTable with alternate colors per row, and a custom color for when the row is selected.

To see it in action, copy and run this code snippet on DartPad.

import 'package:material_ui/material_ui.dart';

/// Flutter code sample for [DataTable].

void main() => runApp(const DataTableExampleApp());

class DataTableExampleApp extends StatelessWidget {
  const DataTableExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('DataTable Sample')),
        body: const DataTableExample(),
      ),
    );
  }
}

class DataTableExample extends StatefulWidget {
  const DataTableExample({super.key});

  @override
  State<DataTableExample> createState() => _DataTableExampleState();
}

class _DataTableExampleState extends State<DataTableExample> {
  static const int numItems = 20;
  List<bool> selected = List<bool>.generate(numItems, (int index) => false);

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: DataTable(
        columns: const <DataColumn>[DataColumn(label: Text('Number'))],
        rows: List<DataRow>.generate(
          numItems,
          (int index) => DataRow(
            color: WidgetStateProperty.resolveWith<Color?>((
              Set<WidgetState> states,
            ) {
              // All rows will have the same selected color.
              if (states.contains(WidgetState.selected)) {
                return Theme.of(
                  context,
                ).colorScheme.primary.withValues(alpha: 0.08);
              }
              // Even rows will have a grey color.
              if (index.isEven) {
                return Colors.grey.withValues(alpha: 0.3);
              }
              return null; // Use default value for other states and odd rows.
            }),
            cells: <DataCell>[DataCell(Text('Row $index'))],
            selected: selected[index],
            onSelectChanged: (bool? value) {
              setState(() {
                selected[index] = value!;
              });
            },
          ),
        ),
      ),
    );
  }
}

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:

Inheritance

Constructors

DataTable({Key? key, required List<DataColumn> columns, int? sortColumnIndex, bool sortAscending = true, ValueSetter<bool?>? onSelectAll, Decoration? decoration, WidgetStateProperty<Color?>? dataRowColor, @Deprecated('Migrate to use dataRowMinHeight and dataRowMaxHeight instead. ' 'This feature was deprecated after v3.7.0-5.0.pre.') double? dataRowHeight, double? dataRowMinHeight, double? dataRowMaxHeight, TextStyle? dataTextStyle, WidgetStateProperty<Color?>? headingRowColor, double? headingRowHeight, TextStyle? headingTextStyle, double? horizontalMargin, double? columnSpacing, bool showCheckboxColumn = true, bool showBottomBorder = false, double? dividerThickness, required List<DataRow> rows, double? checkboxHorizontalMargin, TableBorder? border, Clip clipBehavior = Clip.none})
Creates a widget describing a data table.

Properties

border TableBorder?
The style to use when painting the boundary and interior divisions of the table.
final
checkboxHorizontalMargin double?
Horizontal margin around the checkbox, if it is displayed.
final
clipBehavior Clip
The content will be clipped (or not) according to this option.
final
columns List<DataColumn>
The configuration and labels for the columns in the table.
final
columnSpacing double?
The horizontal margin between the contents of each data column.
final
dataRowColor WidgetStateProperty<Color?>?
The background color for the data rows.
final
dataRowHeight double?
The height of each row (excluding the row that contains column headings).
no setter
dataRowMaxHeight double?
The maximum height of each row (excluding the row that contains column headings).
final
dataRowMinHeight double?
The minimum height of each row (excluding the row that contains column headings).
final
dataTextStyle TextStyle?
The text style for data rows.
final
decoration Decoration?
The background and border decoration for the table.
final
dividerThickness double?
The width of the divider that appears between TableRows.
final
hashCode int
The hash code for this object.
no setterinherited
headingRowColor WidgetStateProperty<Color?>?
The background color for the heading row.
final
headingRowHeight double?
The height of the heading row.
final
headingTextStyle TextStyle?
The text style for the heading row.
final
horizontalMargin double?
The horizontal margin between the edges of the table and the content in the first and last cells of each row.
final
key Key?
Controls how one widget replaces another widget in the tree.
finalinherited
onSelectAll ValueChanged<bool?>?
Invoked when the user selects or unselects every row, using the checkbox in the heading row.
final
rows List<DataRow>
The data to show in each row (excluding the row that contains the column headings).
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
showBottomBorder bool
Whether a border at the bottom of the table is displayed.
final
showCheckboxColumn bool
Whether the widget should display checkboxes for selectable rows.
final
sortAscending bool
Whether the column mentioned in sortColumnIndex, if any, is sorted in ascending order.
final
sortColumnIndex int?
The current primary sort key's column.
final

Methods

build(BuildContext context) Widget
Describes the part of the user interface represented by this widget.
override
createElement() StatelessElement
Creates a StatelessElement to manage this widget's location in the tree.
inherited
debugDescribeChildren() List<DiagnosticsNode>
Returns a list of DiagnosticsNode objects describing this node's children.
inherited
debugFillProperties(DiagnosticPropertiesBuilder properties) → void
Add additional properties associated with the node.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toDiagnosticsNode({String? name, DiagnosticsTreeStyle? style}) DiagnosticsNode
Returns a debug representation of the object that is used by debugging tools and by DiagnosticsNode.toStringDeep.
inherited
toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) String
A string representation of this object.
inherited
toStringDeep({String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, int wrapWidth = 65}) String
Returns a string representation of this node and its descendants.
inherited
toStringShallow({String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) String
Returns a one-line detailed description of the object.
inherited
toStringShort() String
A short, textual description of this widget.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited