Flutter Data Table - How to Sort Data in the Data Table

Published August 19, 2021

In this post we will cover how to use Data Table and update data and sort the data based on data item selection.

What is Data Table

[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

 

Constructor of Data table

DataTable({
  Key? 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,
})

 

 

Download Source code

 

Now Let's implement data table with sorting the list items

Step 1: Create Flutter Application

Step 2: Create a Model class to set data to the Data Rows

class Dessert {
  Dessert(this.name, this.calories, this.fat, this.carbs, this.protein, this.sodium, this.calcium, this.iron,this.select);

   String name;
   int calories;
   double fat;
   int carbs;
   double protein;
   int sodium;
   int calcium;
   int iron;
   bool select;
}

 

Step 3: Now add the data to Data Table

To display this data we will use DataRow property of Data Table and handle selected events by

DataRow(
selected: dessert.select,
  onSelectChanged: ( selected) {
    setState(() {
      dessert.select=!dessert.select;
     // kDesserts.elementAt(kDesserts.indexOf(dessert)).select=!kDesserts.elementAt(kDesserts.indexOf(dessert)).select;
      print('row-selected 12: ${kDesserts.indexOf(dessert) } ${kDesserts.elementAt(kDesserts.indexOf(dessert)).select}');
    });

  },

        )

 

How to sort List in flutter?

To srot list data we will use dart collections sort property on the list object

kDesserts.sort((a,b){

    return compareAsciiUpperCase(a.name, b.name);

}

 

Now run the application

 

Flutter Data Table with Sort list data

 

Complete code for Data table and sort list data in the flutter application

import 'package:flutter/material.dart';
import "package:collection/collection.dart";
class DataTableWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {

    return DataTableWidgetState();
  }

}
class DataTableWidgetState extends State<DataTableWidget>{
  bool sortAscending=false;
  bool selectAll=false;
  int sortIndex=0;
  final List<Dessert> kDesserts = <Dessert>[
    Dessert('Frozen yogurt',                        159,  6.0,  24,  4.0,  87, 14,  1,false),
    Dessert('Ice cream sandwich',                   237,  9.0,  37,  4.3, 129,  8,  1,false),
    Dessert('Eclair',                               262, 16.0,  24,  6.0, 337,  6,  7,false),
    Dessert('Cupcake',                              305,  3.7,  67,  4.3, 413,  3,  8,false),
    Dessert('Gingerbread',                          356, 16.0,  49,  3.9, 327,  7, 16,false),
    Dessert('Jelly bean',                           375,  0.0,  94,  0.0,  50,  0,  0,false),
    Dessert('Lollipop',                             392,  0.2,  98,  0.0,  38,  0,  2,false),
    Dessert('Honeycomb',                            408,  3.2,  87,  6.5, 562,  0, 45,false),
    Dessert('Donut',                                452, 25.0,  51,  4.9, 326,  2, 22,false),
    Dessert('KitKat',                               518, 26.0,  65,  7.0,  54, 12,  6,false),
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(accentColor: Colors.pink),
        home: Scaffold(
          appBar: AppBar(backgroundColor: Colors.pink,title: Text("Flutter Data Table"),),
            body: Column(
      children: [

        DataTable(
          sortColumnIndex: sortIndex,
          sortAscending: sortAscending,

          onSelectAll: ( value) {
            setState(() {
              kDesserts.forEach((element) {
                element.select=!element.select;
              });

            });
          },
          columns: <DataColumn>[
            const DataColumn(
              label: Text('Name'),
              tooltip: 'Name',
            ),
            DataColumn(
              label: const Text('Calories'),
              tooltip: 'Calories',
              numeric: true,
              onSort: (int columnIndex, bool ascending) {
                log.add('column-sort: $columnIndex $ascending');
              },
            ),
          ],
          rows: kDesserts.map<DataRow>((Dessert dessert) {
            return DataRow(
            selected: dessert.select,
              onSelectChanged: ( selected) {
                setState(() {
                  dessert.select=!dessert.select;
                 // kDesserts.elementAt(kDesserts.indexOf(dessert)).select=!kDesserts.elementAt(kDesserts.indexOf(dessert)).select;
                  print('row-selected 12: ${kDesserts.indexOf(dessert) } ${kDesserts.elementAt(kDesserts.indexOf(dessert)).select}');
                });

              },
              cells: <DataCell>[
                DataCell(
                  Text(dessert.name),
                ),
                DataCell(
                  Text('${dessert.calories}'),
                  showEditIcon: true,
                  onTap: () {

                  },
                ),
              ],
            );
          }).toList(),
        ),
        MaterialButton(
          color: Colors.pink,
          textColor: Colors.white,
          child: Text("Sort"),
          onPressed: (){
            setState(() {
              sortAscending=!sortAscending;
              kDesserts.sort((a,b){
                if(sortAscending)
                  return compareAsciiUpperCase(a.name, b.name);
                else return compareAsciiUpperCase(b.name, a.name);
              });
            });
          },),
      ],
    )));
  }

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

}
class Dessert {
  Dessert(this.name, this.calories, this.fat, this.carbs, this.protein, this.sodium, this.calcium, this.iron,this.select);

   String name;
   int calories;
   double fat;
   int carbs;
   double protein;
   int sodium;
   int calcium;
   int iron;
   bool select;
}

 

 

Conclusion: In this flutter example we covered how to use Data Table and sort list data with collections property of Sort.

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1864 Views