DataTable in Flutter | Creating Effective Tables

DataTable in Flutter | Creating Effective Tables

DataTable is a Widget in Flutter which is primarily focused at creating simple yet effective ways to create tables in Flutter. The important part of creating Tables in Flutter is that there is not a simple way that the flutter engine recreates them when the data changes. To quote the exact statement from the flutter doc,

“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”.

This is the primary reason we can jump to a PaginatedDataTable. However, we will look at the simple yet effective DataTable widget and create a good Table with Columns and rows in this article.

Before we jump into the article, do read about Stateful Widgets in the tutorial post on how to create Stateful and Stateless Widgets.

DataTable Basics

DataTable is created using the Widget DataTable itself. This uses the following constructor,

DataTable({Key key@required List<DataColumn> columnsint sortColumnIndexbool sortAscendingtrueValueSetter<bool> onSelectAll@required List<DataRow> rows })
The Constructor does use a lot of properties which we will see in detail below. Even before we jump into learning about DataTable in flutter, we will create a simple template as always below.

import 'package:flutter/material.dart';

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

class DataTableWidget extends StatefulWidget {

  @override
  _DataTableWidgetState createState() {
    return _DataTableWidgetState();}}

    class _DataTableWidgetState extends State {
    @override
    Widget build(BuildContext context){
      return MaterialApp(title: 'Androidmonks',
        home: Scaffold(
          appBar: AppBar(title: Text("Sample Data Table"),),

        backgroundColor: Colors.redAccent,
        ),
    );
  }
}

We have used a simple Scaffold as the parent widget before using the other widgets. Make sure to always have a Parent widget which inherits the MediaQuery widget.

To know more about Scaffold, see Scaffold widgets in Flutter application.

DataTable – Properties

columns

First property under DataTable is the column attribute. The important part of the column attribute is that it creates the vertical slots and defines the Column header for which the data has to be arranged.

In order to create a good DataTable widget, the column attribute is required, along with that, the Widget DataColumn is to be used.

DataColumn is a widget that comes under the DataTable Widget family. It contains simple properties including label(Which is the only attribute that is important for us in this article). The Label lets us define the column header for categorization of the Data.

To create columns in DataTable see the example below,

import 'package:flutter/material.dart';

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

class DataTableWidget extends StatefulWidget {

  @override
  _DataTableWidgetState createState() {
    return _DataTableWidgetState();}}

    class _DataTableWidgetState extends State {
    @override
    Widget build(BuildContext context){
      return MaterialApp(title: 'Androidmonks',
        home: Scaffold(
          appBar: AppBar(title: Text("Sample Data Table"),),

        backgroundColor: Colors.redAccent,
        body: Center(child: DataTable(
          columns: [
            DataColumn(
              label: Text("Column1")),
            DataColumn(label: Text("Column2"))],
          rows: [],

        ),
        ),
      ),
    );
  }
}

Remember to give an empty row in order to let the engine know that the DataTable is actually constructed. If the row is not specified the app will not go past the Build stage.

Once done, the application looks like below,

DataColumn in DataTable widget
DataColumn in DataTable widget
rows

Similar to the columns attribute, the row lets you actually define the Data that has to go into the Table. Each column can have any number of rows, but all columns should be filled. Meaning the cells cannot be empty incase there is no data to be filled. You need to make sure an empty value is stored in that position.

To start with the rows attribute, we will require a widget named,

DataRow

The DataRow widget holds the individual rows data. Eg, row1 is represented using a DataRow widget and Row2 with another DataRow widget.

Under each DataRow widget, there is a cell attribute which requires a DataCell Widget as its value. Meaning, the DataCell can hold one value of Data per Widget. If there are 2 columns then each DataRow should hold 2 DataCells.

In case there is a missing DataCell in each row, the application will not build!

If this part is a bit confusing, take a look at the following code to understand better.

import 'package:flutter/material.dart';

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

class DataTableWidget extends StatefulWidget {

  @override
  _DataTableWidgetState createState() {
    return _DataTableWidgetState();}}

    class _DataTableWidgetState extends State {
    @override
    Widget build(BuildContext context){
      return MaterialApp(title: 'Androidmonks',
        home: Scaffold(
          appBar: AppBar(title: Text("Sample Data Table"),),

        backgroundColor: Colors.redAccent,
        body: Center(child: DataTable(
          columns: [
            DataColumn(
              label: Text("Column1")),
            DataColumn(label: Text("Column2"))],
          rows: [
            DataRow(cells: [
            DataCell(Text("1")),
          DataCell(Text("ZZZZ2")),]),
          DataRow(cells: [DataCell(Text("2")),
          DataCell(Text("asc-cell2"))
            ,]),],

        ),
        ),
      ),
    );
  }
}

Since we have specified that there will be 2 Rows, we have given 2 DataRow as value for the rows attribute.

The application now looks like,

DataTable with Row attribute
DataTable with Row attribute

 

sortColumnIndex

SortColumnIndex is a simple attribute that takes in an Integer value. It lets the developer define which is the primary key( Meaning unique column) in the DataTable. This is effectively used for sorting of the Rows in the Table directly, which we will look at in the next section.

To define the sortColumnIndex, see the below example,

import 'package:flutter/material.dart';

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

class DataTableWidget extends StatefulWidget {

  @override
  _DataTableWidgetState createState() {
    return _DataTableWidgetState();}}

    class _DataTableWidgetState extends State {
    @override
    Widget build(BuildContext context){
      return MaterialApp(title: 'Androidmonks',
        home: Scaffold(
          appBar: AppBar(title: Text("Sample Data Table"),),

        backgroundColor: Colors.redAccent,
        body: Center(child: DataTable(
          columns: [
            DataColumn(
              label: Text("Column1")),
            DataColumn(label: Text("Column2"))],
          rows: [
            DataRow(cells: [
            DataCell(Text("1")),
          DataCell(Text("ZZZZ2")),]),
          DataRow(cells: [DataCell(Text("2")),
          DataCell(Text("asc-cell2"))
            ,]),],
          sortColumnIndex: 0,
        ),
        ),
      ),
    );
  }
}

This lets the engine know that the First Column is going to be the Primary key for the entire Table.

sortAscending

Sort Ascending attribute change the Table values and sort it in the ascending order of the Column Index that was given in the above section. Meaning, the entire Data Table is rearranged with the Column Index as the primary key.

This will help the user categorize the data he wants to see.

See the example code below,

import 'package:flutter/material.dart';

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

class DataTableWidget extends StatefulWidget {

  @override
  _DataTableWidgetState createState() {
    return _DataTableWidgetState();}}

    class _DataTableWidgetState extends State {
    @override
    Widget build(BuildContext context){
      return MaterialApp(title: 'Androidmonks',
        home: Scaffold(
          appBar: AppBar(title: Text("Sample Data Table"),),

        backgroundColor: Colors.redAccent,
        body: Center(child: DataTable(
          columns: [
            DataColumn(
              label: Text("Column1")),
            DataColumn(label: Text("Column2"))],
          rows: [
            DataRow(cells: [
            DataCell(Text("1")),
          DataCell(Text("ZZZZ2")),]),
          DataRow(cells: [DataCell(Text("2")),
          DataCell(Text("asc-cell2"))
            ,]),],
          sortColumnIndex: 0,
          sortAscending: true,
        ),
        ),
      ),
    );
  }
}

The application becomes,

Column Index is defined and represented with an arrow
Column Index is defined and represented with an arrow

The arrow coming up in the first column defines what is to be considered as the column Index. This way the data can be changed by the end user.

Putting it all together

Once the entire application is stitched together, it becomes easy to create a better-looking DataTable with effective control over what is displayed.

Note: Use data table for smaller sets of values only, since it can become slow to load and refresh if a larger volume of data is given.

Drop in any comments in the section below.

“Learn and Be Curious”

Leave a Comment

Your email address will not be published. Required fields are marked *