Ask Your Question
0

How to implement the built-in sorting function of DataTable in Flutter?

asked 2022-07-11 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-05-17 14:00:00 +0000

david gravatar image

To implement the built-in sorting function of DataTable in Flutter, you can follow these steps:

  1. Create a DataTable widget with the columns you need.
DataTable(
  columns: [
    DataColumn(label: Text('Name')),
    DataColumn(label: Text('Age')),
    DataColumn(label: Text('Gender')),
  ],
  rows: // ...
)
  1. Create a List of data that you want to display in the DataTable.
List<DataRow> dataRows = [
  DataRow(cells: [
    DataCell(Text('John')),
    DataCell(Text('25')),
    DataCell(Text('Male')),
  ]),
  DataRow(cells: [
    DataCell(Text('Mary')),
    DataCell(Text('30')),
    DataCell(Text('Female')),
  ]),
  // ...
];
  1. Create a SortColumnCallback function that will handle the sorting of data.
int _sortColumnIndex = 0;
bool _sortAscending = true;

void _sortList(SortColumnIndex? index, bool ascending) {
  setState(() {
    _sortColumnIndex = index!;
    _sortAscending = ascending;

    dataRows.sort((a, b) {
      if (a.cells[_sortColumnIndex].child is Text) {
        String? aText = (a.cells[_sortColumnIndex].child as Text).data;
        String? bText = (b.cells[_sortColumnIndex].child as Text).data;

        return _sortAscending
            ? Comparable.compare(aText, bText)
            : Comparable.compare(bText, aText);
      } else {
        return 0;
      }
    });
  });
}
  1. Add the onSort callback to your DataColumn widgets, and pass the _sortList function.
DataColumn(
  label: Text('Name'),
  onSort: ( columnIndex, ascending) {
    _sortList(columnIndex, ascending);
  }
),
  1. Finally, build the DataTable widget and pass the sorted data to the rows parameter.
DataTable(
  columns: [
    DataColumn(label: Text('Name'), onSort: (index, ascending) => _sortList(index, ascending)),
    DataColumn(label: Text('Age'), onSort: (index, ascending) => _sortList(index, ascending)),
    DataColumn(label: Text('Gender'), onSort: (index, ascending) => _sortList(index, ascending)),
  ],
  rows: dataRows,
)

That's it. Now you have a DataTable with built-in sorting functionality that can sort your data by each column.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-11 11:00:00 +0000

Seen: 8 times

Last updated: May 17 '22