【笔记】Flutter的DataTable表格

前言

Flutter的DataTable表格学习笔记

DataTable表格

columns:定义表头
rows:定义表体

定义表头的属性的属性

numeric:当前列对齐方式

false:缺省值,左对齐
true:右对齐

tooltip:长按当前列头提示文本内容

定义表体的属性

showEditIcon:显示编辑按钮
placeholder:显示为默认文本,通常用于可编辑的文本
onTap:单元格被点击事件

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
DataTable(
columns: <DataColumn>[
const DataColumn(
label: Text("行1列1"),
numeric: false,
tooltip: "文本内容",
),
const DataColumn(label: Text("行1列2")),
],
rows: <DataRow>[
DataRow(
cells: [
DataCell(
Text("行2列1"),
showEditIcon: true,
placeholder: true,
onTap: (){
...
},
),
DataCell(Text("行2列2")),
],
),
DataRow(
cells: [
DataCell(Text("行3列1")),
DataCell(Text("行3列2")),
],
),
],
)

行可选的表格

实体类中添加属性

1
2
3
4
5
6
7
8
9
10
11
class User {
late int id;
late String name;
late bool selected; // 选中状态

User({
required this.id,
required this.name,
required this.selected,
});
}

创建对象

1
2
3
4
List<User> userList = <User>[
User(id: 1, name: "张三", selected: false),
User(id: 2, name: "李四", selected: false),
];

渲染表格

selected:当前行默认的选中状态

false:缺省值,没被选中
true:被选中

onSelectChanged:在第一列之前新增一列复选框,同时在行被点击时执行回调函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
DataTable(
// 定义表头
columns: <DataColumn>[
const DataColumn(label: Text("id")),
const DataColumn(label: Text("name")),
],
// 定义表体
rows: userList.map((user) {
return DataRow(
cells: [
DataCell(Text("${user.id}")),
DataCell(Text("${user.name}")),
],
selected: user.selected,
onSelectChanged: (selected) {
setState(() {
user.selected = selected!;
});
},
);
}).toList(),
)

可排序的表格

实体类中定义属性

1
2
3
4
5
6
7
8
9
class User {
late int id;
late String name;

User({
required this.id,
required this.name,
});
}

创建对象

1
2
3
4
5
6
List<User> userList = <User>[
User(id: 2, name: "张三"),
User(id: 1, name: "李四"),
User(id: 4, name: "王五"),
User(id: 3, name: "赵六"),
];

定义默认的排序方式

1
bool _sortAscending = true;

渲染表格

sortColumnIndex:定义被排序的列,该列会多出一个箭头图标,向上表示正序,向下表示倒序
sortAscending:定义排序方式

true:缺省值,正序(从小到大)
false:倒序(从大到小)

onSort:点击表头后执行排序回调函数,函数内实现排序算法进行排序

columnIndex:当前列索引
ascending:排序方式

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
DataTable(
// 定义表头
columns: <DataColumn>[
DataColumn(
sortColumnIndex: 0,
sortAscending: _sortAscending,
label: Text("id"),
onSort: (int columnIndex, bool ascending) {
setState(() {
_sortAscending = ascending;
if (ascending) {
// 正序
userList.sort((a, b) => a.id.compareTo(b.id));
} else {
// 倒序
userList.sort((a, b) => b.id.compareTo(a.id));
}
});
}
),
const DataColumn(label: Text("name")),
],
// 定义表体
rows: userList.map((user) {
return DataRow(cells: [
DataCell(Text("${user.id}")),
DataCell(Text("${user.name}")),
]);
}).toList(),
)

解决数据显示不全的问题

  • 通过SingleChildScrollView包裹表格
1
2
3
4
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable()
)

完成

参考文献

稀土掘金——岛上码农
CSDN——老孟Flutter