Skip to content

Instantly share code, notes, and snippets.

@pawar-aniket
Last active April 13, 2020 09:30
Show Gist options
  • Save pawar-aniket/fdca6226e953881e78e98d780dd90af6 to your computer and use it in GitHub Desktop.
Save pawar-aniket/fdca6226e953881e78e98d780dd90af6 to your computer and use it in GitHub Desktop.
class _DataTableExample extends State<DataTableExample> {
List<Map> data;
bool sort;
int iSortColumnIndex;
@override
void initState() {
sort = true; // Note that in flutter ascending/descending icon are inversed
iSortColumnIndex = 1;
onCountSortColum(1, true);
super.initState();
}
onNameSortColum(int columnIndex, bool ascending) {
if (columnIndex == 0) {
// Flutter considers the ascending logo as (↓) and descending icon as (↑).
// Due to that fact descending order mechanism is being written in ascending block.
if (ascending) {
data.sort((a, b) => b['name'].compareTo(a['name']));
} else {
data.sort((a, b) => a['name'].compareTo(b['name']));
}
}
}
onCountSortColum(int columnIndex, bool ascending) {
if (columnIndex == 1) {
// Flutter considers the ascending logo as (↓) and descending icon as (↑).
// Due to that fact descending order mechanism is being written in ascending block.
if (ascending) {
data.sort(
(a, b) => b['count'].compareTo(a['count']));
} else {
data.sort(
(a, b) => a['count'].compareTo(b['count']));
}
}
}
List<DataRow> _buildDataRows() {
return data
.map(
(obj) => DataRow(cells: [
DataCell(
Text('${obj["name"]}'),
),
DataCell(Text('${obj["count"]}')),
]),
)
.toList();
}
Widget _buildDataTable() {
return DataTable(
sortColumnIndex: iSortColumnIndex,
sortAscending: sort,
columns: [
DataColumn(
onSort: (columnIndex, ascending) {
setState(() {
sort = ascending;
iSortColumnIndex = columnIndex;
});
onNameSortColum(columnIndex, ascending);
},
label: Text('Name',
style: TextStyle(
fontWeight: FontWeight.bold,
letterSpacing: 1.0,
))),
DataColumn(
onSort: (columnIndex, ascending) {
setState(() {
sort = ascending;
iSortColumnIndex = columnIndex;
});
onCountSortColum(columnIndex, ascending);
},
label: Text('Count',
style: TextStyle(
fontWeight: FontWeight.bold,
letterSpacing: 1.0,
)),
),
],
rows: _buildDataRows(),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'DataTable Example',
),
centerTitle: true,
),
body: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: _buildDataTable(),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment