To implement the built-in sorting function of DataTable in Flutter, you can follow these steps:
DataTable(
columns: [
DataColumn(label: Text('Name')),
DataColumn(label: Text('Age')),
DataColumn(label: Text('Gender')),
],
rows: // ...
)
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')),
]),
// ...
];
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;
}
});
});
}
DataColumn(
label: Text('Name'),
onSort: ( columnIndex, ascending) {
_sortList(columnIndex, ascending);
}
),
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.
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
Asked: 2022-07-11 11:00:00 +0000
Seen: 12 times
Last updated: May 17 '22
What is the process of using the Multmerge() function in r to combine files in a directory?
Is it possible for two distinct useState functions to trigger changes simultaneously?
How can one use node to change an ogg file into an mp3 file?
How can a function pointer be transferred between different files in CUDA?
What does the error message "TypeError: e.endsWith is not a function" mean in Redoc?
What is the expected outcome of the math.floor function in terms of the return value?