1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| class Student{ String name; int age; String school; bool selected; Student(this.name,this.age,this.school,{this.selected=false}); }
class MyPage extends StatefulWidget { const MyPage({Key? key}) : super(key: key); @override State<MyPage> createState() => _MyPageState(); }
class _MyPageState extends State<MyPage> { bool asc=true; List<Student> students=[ Student("阿东", 21, "Three Gorges"), Student("阿叶", 20, "Three Gorges") ];
getStudentsData(){ List<DataRow> dataRows=[]; for (var element in students) { dataRows.add(DataRow( selected: element.selected, onSelectChanged: (selected){ setState(() { element.selected=selected!; }); }, cells: [ DataCell(Text(element.name)), DataCell(Text("${element.age}")), DataCell(Text(element.school)) ] )); } return dataRows; } @override Widget build(BuildContext context) { return SingleChildScrollView( physics: const BouncingScrollPhysics(), child: DataTable( sortColumnIndex: 1, sortAscending: asc, columns: [ const DataColumn(label: Text("name")), DataColumn( label: const Text("age"), numeric: true, onSort: (int index,bool toBeAsc){ setState(() { asc=toBeAsc; if(toBeAsc){ students.sort((a,b) => a.age.compareTo(b.age)); } else { students.sort((a,b) => b.age.compareTo(a.age)); } }); } ), const DataColumn(label: Text("school")) ], rows: getStudentsData(), ), ); } }
|