- DataTable 应该是 StatefulWidget 的一部分
- 每当需要在不同的列上进行排序时,就需要重新渲染 StatefulWidget 所包含的小部件
- 为了触发重新渲染,我们应该在
onSort: (columnIndex, ascending) {}
中添加 setState(() {})
方法,如下所示:
DataColumn(
label: const Text(
'Name',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) {
print("columnIndex:$columnIndex");
print("ascending:$ascending");
setState(() {
sortColumnIndex = columnIndex;
isAscending = ascending;
});
每次单击列标题时,都会调用onSort: (columnIndex, ascending) {}
。
DataTable应该有状态变量,例如sortColumnIndex
,以便对不同列进行排序点击时重置此索引,并且相应的索引列将获得箭头图标。
child: DataTable(
border: TableBorder.symmetric(),
sortAscending: isAscending,
sortColumnIndex: sortColumnIndex,
6. 如果再次按同一列,则 isAscending 将用于反转箭头。
7. 与 sortColumnIndex 状态变量类似,我们必须手动对表格数据进行排序,以便在单击后呈现新的排序值。
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
var isAscending = true;
var sortColumnIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: DataTable(
border: TableBorder.symmetric(),
sortAscending: isAscending,
sortColumnIndex: sortColumnIndex,
columns: <DataColumn>[
DataColumn(
label: const Text(
'Name',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) {
print("columnIndex:$columnIndex");
print("ascending:$ascending");
setState(() {
sortColumnIndex = columnIndex;
isAscending = ascending;
});
},
),
DataColumn(
label: const Text(
'Age',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) {
print("columnIndex:$columnIndex");
print("ascending:$ascending");
setState(() {
sortColumnIndex = columnIndex;
isAscending = ascending;
});
},
),
DataColumn(
label: const Text(
'Role',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) {
print("columnIndex:$columnIndex");
print("ascending:$ascending");
setState(() {
sortColumnIndex = columnIndex;
isAscending = ascending;
});
},
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('Sarah')),
DataCell(Text('19')),
DataCell(Text('Student')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Janine')),
DataCell(Text('43')),
DataCell(Text('Professor')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('William')),
DataCell(Text('27')),
DataCell(Text('Associate Professor')),
],
),
],
),
),
);
}
}
sortColumnIndex
只会影响标题行中的指示箭头。数据行不会自动排序。您应该手动对数据进行排序,然后调用setState
。 - Pavel