在Flutter DataTable中对列值进行排序 [英] Sorting Column Values in Flutter DataTable
问题描述
我很难对DataTable中的列进行排序.
I am having serious difficulty in sorting columns in my DataTable.
这是我的代码
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
sortColumnIndex: 0,
sortAscending: true,
columnSpacing: 5.0,
horizontalMargin: 10,
columns: [
DataColumn(label: Text('Col1'),
DataColumn(label: Text('Col2'),numeric: false ),
DataColumn(label: Text('Col3'),numeric: true ),
DataColumn(label: Text('Col4'), numeric: true),
DataColumn(label: Text('Col5'), numeric: true),
],
rows: myList
.map(
((element) => DataRow(
cells: <DataCell>[
DataCell(Text(element["Col1"]), placeholder: true,showEditIcon: false),
DataCell(Text(element["Col2"].toString())),
DataCell(Text(element["Col3"].toString())),
DataCell(Text(element["Col4"].toString())),
DataCell(Text(element["Col5"].toString())),
],
)),
).toList(),
),
));
我还要做什么?理想情况下,我希望在用户按下的任何列上都具有排序功能,但就目前而言,我很高兴只有1列可以进行排序.
What more am I meant to do? Ideally, I'd like to have the sort function on whichever column the user presses on, but for now, I'd be delighted with just 1 column working being sortable.
如您所见,我添加了约束:
As you can see, I have added the constraints:
sortColumnIndex: 0,
sortAscending: true,
但是我所得到的只是第一列附近的箭头(ColumnIndex = 0)-当您按下它时,它实际上什么也没做.
But all I get is an arrow near 1st column (ColumnIndex = 0) - which really does nothing when you press it.
我做错了什么?
推荐答案
您必须在要排序的列中添加"onSort:",然后调用排序功能.
You have to add a 'onSort: ,' to the column that will be sorted, and call a sorting function.
bool sort;
DataTable(
sortAscending: sort,
sortColumnIndex: 0,
columns: [
DataColumn(
label: Text("Col1"),
onSort: (columnIndex, ascending) {
setState(() {
sort = !sort;
});
onSortColum(columnIndex, ascending);
}),
...
和onSortColum函数:
And the onSortColum function:
onSortColum(int columnIndex, bool ascending) {
if (columnIndex == 0) {
if (ascending) {
yourDataList.sort((a, b) => a['name'].compareTo(b['name']));
} else {
yourDataList.sort((a, b) => b['name'].compareTo(a['name']));
}
}
}
希望有帮助!
这篇关于在Flutter DataTable中对列值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!