Flutter DataTable

If you have fewer rows to display in a table, you can use DataTable.

DataTable is a materaial design data table where you can display a table with column labels and rows.

Note: Use DataTable if and only if you have fewer rows, because DataTable takes twice the computation for laying out elements on UI.

Syntax

Following is the syntax of a DataTable.

DataTable(
  columns: [
	DataColumn(label: ),
	DataColumn(label: ),
	...
	DataColumn(label: )),
  ],
  rows: [
	DataRow(cells: [
	  DataCell( ),
	  DataCell( ),
	  ...
	  DataCell( ),
	]),
	DataRow(cells: [
	  DataCell( ),
	  DataCell( ),
	  ...
	  DataCell( ),
	]),
	...
	DataRow(cells: [
	  DataCell( ),
	  DataCell( ),
	  ...
	  DataCell( ),
	]),
  ],
),

DataTable contains columns and rows. columns property takes array of DataColumn and rows property takes array of DataRow. Each DataRow has cells property that takes array of DataCell.

label property of DataColumn takes Widget as value. Also DataCell takes widget as a value. You can provide Text, Image, Icon, or any other widget.

ADVERTISEMENT

Example

In the following example, we define a simple DataTable with three column labels and three rows.

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Flutter Tutorial - TutorialKart'),
          ),
          body: ListView(children: <Widget>[
            Center(
                child: Text(
              'Students',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            )),
            DataTable(
              columns: [
                DataColumn(label: Text('RollNo')),
                DataColumn(label: Text('Name')),
                DataColumn(label: Text('Class')),
              ],
              rows: [
                DataRow(cells: [
                  DataCell(Text('1')),
                  DataCell(Text('Arya')),
                  DataCell(Text('6')),
                ]),
                DataRow(cells: [
                  DataCell(Text('12')),
                  DataCell(Text('John')),
                  DataCell(Text('9')),
                ]),
                DataRow(cells: [
                  DataCell(Text('42')),
                  DataCell(Text('Tony')),
                  DataCell(Text('8')),
                ]),
              ],
            ),
          ])),
    );
  }
}

When you run this Flutter application, you would get the DataTable displayed in UI as shown below.

Flutter DataTable

Conclusion

In this Flutter Tutorial, we learned how to define DataTable and display a data table in Flutter UI.