Flutter数据表格展示插件fdatatable的使用
Flutter 数据表格展示插件 fdatatable 的使用
在本指南中,我们将详细介绍如何在 Flutter 中使用 fdatatable
插件来展示数据表格。fdatatable
插件提供了分页、过滤等功能,并且支持自定义列和操作。
特性
- 分页
- 过滤
- 响应式布局
安装
首先,在你的 pubspec.yaml
文件中添加 fdatatable
依赖:
dependencies:
fdatatable: ^x.x.x
然后运行 flutter pub get
命令安装依赖。
设置
创建一个新的 FDT<DType>
实例:
FDT<Model>(
fdtRequest: (requestModel) async {
await Future.delayed(Duration(seconds: 2));
return FDTResponseModel(
page: requestModel.page,
pageSize: requestModel.pageSize,
total: 100,
list: _exampleModels(requestModel.pageSize)
);
},
columns: [],
filters: [],
)
定义列
定义你想要展示的列:
FDTBaseColumn(
title: "User Name",
cellBuilder: (item) => Text(item.userName),
columnWidth: 50,
isExpand: true,
)
定义过滤器
定义你想要使用的过滤器类型:
FDT<Model>(
filters: [
FDTTextFilter(
key: "name",
val: "initValue",
),
]
)
过滤器类型
FDTTextFilter
FDTIntFilter
FDTCheckboxFilter
FDTDropDownFilter<FType>
FDTDateFilter
顶部菜单
定义顶部菜单按钮:
FDT<Model>(
...
topActions: const [
FDTAction(text: "New", action: FDTActionTypes.add, icon: Icon(Icons.plus_one_outlined, color: Colors.blue,)),
FDTAction(text: "Refresh", action: FDTActionTypes.refresh, icon: Icon(Icons.refresh_outlined,)),
FDTAction(text: "To Page 10", action: FDTActionTypes.toPage, icon: Icon(Icons.arrow_circle_right_outlined,)),
]
)
行菜单
定义行操作按钮:
FDT<Model>(
...
rowActions: const [
FDTAction(text: "Edit", action: FDTActionTypes.edit, icon: Icon(Icons.edit,)),
FDTAction(text: "Delete", action: FDTActionTypes.delete,
icon: Icon(Icons.delete_forever, color: Colors.red,)
),
FDTAction(text: "Info", action: FDTActionTypes.info,
icon: Icon(Icons.info, color: Colors.red,)
)
],
)
完整示例
以下是一个完整的示例代码,展示了如何使用 fdatatable
插件来展示数据表格。
import 'dart:html';
import 'package:f_json_editor/f_json_editor.dart';
import 'package:fdatatable_example/Model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fdatatable/fdatatable.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late FDTController<Model> dataTableController;
late List<FDTBaseColumn<Model>> columns;
late List<FDTFilter> filters;
[@override](/user/override)
void initState() {
super.initState();
dataTableController = FDTController();
columns = [
FDTBaseColumn<Model>(
title: "Name",
cellBuilder: (item) {
return Text(item.firstName);
},
columnWidth: 75,
),
FDTBaseColumn<Model>(
title: "Last Name",
cellBuilder: (item) {
return Text(item.lastName);
},
),
FDTBaseColumn<Model>(
title: "E-mail",
cellBuilder: (item) {
return Text(item.email);
},
columnWidth: 100,
),
FDTBaseColumn<Model>(
title: "Full Name",
cellBuilder: (item) {
return Text(item.firstName + " " + item.lastName);
},
),
FDTBaseColumn<Model>(
title: "Active",
cellBuilder: (item) {
if (item.isActive) {
return Text("Active", style: TextStyle(color: Colors.green));
} else {
return Text("Passive", style: TextStyle(color: Colors.red));
}
},
columnWidth: 100,
),
FDTBaseColumn<Model>(
title: "Age",
cellBuilder: (item) {
return Text(item.age.toString());
},
columnWidth: 50,
isExpand: true,
),
FDTBaseColumn<Model>(
title: "Gender",
cellBuilder: (item) {
return Text(item.gender);
},
),
FDTBaseColumn<Model>(
title: "User Type",
cellBuilder: (item) {
if (item.userType == 1) {
return Row(
children: [
Icon(Icons.add_moderator_outlined, color: Colors.red),
Text("SuperAdmin")
],
);
} else {
return Row(
children: [
Icon(CupertinoIcons.textformat_size, color: Colors.red),
Text("Guest")
],
);
}
},
),
FDTBaseColumn<Model>(
isExpand: true,
title: "Detail",
cellBuilder: (item) {
return Text(item.detail);
}
),
FDTBaseColumn<Model>(
title: "Date",
isExpand: true,
cellBuilder: (item) {
return SizedBox(
height: 200,
child: FJSONEditor(
showHeader: true,
isEditable: false,
jsonData: {
"key1": "val1",
"key2": 2,
"key3": ["ff", "ff"]
},
actionCallback: (actionKey, jsonData) {},
),
);
},
columnWidth: 250,
),
];
filters = [
FDTTextFilter(
key: "name",
decoration: InputDecoration(
labelText: "fieldName",
contentPadding: EdgeInsets.all(1),
border: const OutlineInputBorder(),
focusedBorder: OutlineInputBorder(),
),
),
FDTIntFilter(
key: "intkey",
decoration: InputDecoration(
labelText: "fieldName",
contentPadding: EdgeInsets.all(1),
border: const OutlineInputBorder(),
focusedBorder: OutlineInputBorder(),
)
),
FDTCheckboxFilter(
key: "aktive",
decoration: InputDecoration(
labelText: "fieldName",
contentPadding: EdgeInsets.all(1),
border: const OutlineInputBorder(),
focusedBorder: OutlineInputBorder(),
)
),
FDTDropDownFilter<String>(
key: "drop",
itemBuilder: () async {
debugPrint("get items");
await Future.delayed(Duration(seconds: 1));
return [
DropdownMenuItem<String>(
value: "admin",
child: Text("Admin2"),
),
DropdownMenuItem<String>(
value: "superadmin2",
child: Text("SuperAdmin"),
)
];
},
decoration: InputDecoration(
labelText: "fieldName",
contentPadding: EdgeInsets.all(1),
border: const OutlineInputBorder(),
focusedBorder: OutlineInputBorder(),
)
),
FDTDateFilter(
key: "date",
decoration: InputDecoration(
labelText: "fieldName",
contentPadding: EdgeInsets.all(1),
border: const OutlineInputBorder(),
focusedBorder: OutlineInputBorder(),
)
)
];
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.dark,
darkTheme: ThemeData.dark(useMaterial3: true),
home: Scaffold(
appBar: AppBar(
title: const Text('FDataTable example app'),
),
body: Container(
child: Padding(
padding: EdgeInsets.all(20),
child: Center(
child: FDT<Model>(
title: Text("User list Table"),
fdtRequest: (requestModel) async {
await Future.delayed(Duration(seconds: 2));
print("request");
print(requestModel.filters);
return FDTResponseModel(
page: requestModel.page,
pageSize: requestModel.pageSize,
total: 100,
list: _exampleModels(requestModel.pageSize)
);
},
controller: dataTableController,
columns: columns,
filters: filters,
showHeader: false,
expandableRow: true,
actionCallBack: (action) {
switch (action.action) {
case FDTActionTypes.delete:
dataTableController.removeAt(action.index);
case FDTActionTypes.refresh:
dataTableController.refreshPage();
case FDTActionTypes.toPage:
dataTableController.toPage(10);
case FDTActionTypes.add:
default:
break;
}
},
rowActions: const [
FDTAction(text: "Edit", action: FDTActionTypes.edit, icon: Icon(Icons.edit,)),
FDTAction(text: "Delete", action: FDTActionTypes.delete,
icon: Icon(Icons.delete_forever, color: Colors.red,)
),
FDTAction(text: "Info", action: FDTActionTypes.info,
icon: Icon(Icons.info, color: Colors.red,)
)
],
),
),
),
),
),
);
}
List<Model> _exampleModels(int count) {
return List.generate(count, (index) {
return Model(
id: "id" + index.toString(),
firstName: "name" + index.toString(),
lastName: "surname" + index.toString(),
email: "example@gmail.com",
age: index,
isActive: index % 2 == 0 ? true : false,
gender: "Male",
birthDate: DateTime.now(),
detail: "No detail",
userType: index % 3,
);
},);
}
}
更多关于Flutter数据表格展示插件fdatatable的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter数据表格展示插件fdatatable的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
fdatatable
是一个用于在 Flutter 中展示数据表格的插件。它提供了丰富的功能,例如分页、排序、筛选等,非常适合用于展示大量数据的场景。以下是如何使用 fdatatable
插件的基本步骤和示例代码。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 fdatatable
插件的依赖:
dependencies:
flutter:
sdk: flutter
fdatatable: ^0.1.0 # 请使用最新版本
然后运行 flutter pub get
以安装依赖。
2. 导入包
在 Dart 文件中导入 fdatatable
包:
import 'package:fdatatable/fdatatable.dart';
3. 创建数据表格
以下是一个简单的示例,展示如何使用 fdatatable
创建一个基本的表格:
import 'package:flutter/material.dart';
import 'package:fdatatable/fdatatable.dart';
class MyDataTablePage extends StatelessWidget {
final List<Map<String, dynamic>> data = [
{'id': 1, 'name': 'Alice', 'age': 25},
{'id': 2, 'name': 'Bob', 'age': 30},
{'id': 3, 'name': 'Charlie', 'age': 35},
{'id': 4, 'name': 'David', 'age': 40},
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('DataTable Example'),
),
body: FDataTable(
columns: [
FDataColumn(label: Text('ID')),
FDataColumn(label: Text('Name')),
FDataColumn(label: Text('Age')),
],
rows: data.map((item) {
return FDataRow(
cells: [
FDataCell(Text(item['id'].toString())),
FDataCell(Text(item['name'])),
FDataCell(Text(item['age'].toString())),
],
);
}).toList(),
),
);
}
}
void main() {
runApp(MaterialApp(
home: MyDataTablePage(),
));
}
4. 分页和排序
fdatatable
支持分页和排序功能。以下是如何启用这些功能的示例:
FDataTable(
columns: [
FDataColumn(label: Text('ID'), sortable: true),
FDataColumn(label: Text('Name'), sortable: true),
FDataColumn(label: Text('Age'), sortable: true),
],
rows: data.map((item) {
return FDataRow(
cells: [
FDataCell(Text(item['id'].toString())),
FDataCell(Text(item['name'])),
FDataCell(Text(item['age'].toString())),
],
);
}).toList(),
pagination: FPagination(
pageSize: 2,
onPageChanged: (page) {
print('Page changed to $page');
},
),
onSort: (columnIndex, ascending) {
print('Sorting by column $columnIndex, ascending: $ascending');
},
)
5. 筛选功能
fdatatable
也支持筛选功能。你可以通过设置 filterable
属性来启用筛选功能:
FDataTable(
columns: [
FDataColumn(label: Text('ID'), filterable: true),
FDataColumn(label: Text('Name'), filterable: true),
FDataColumn(label: Text('Age'), filterable: true),
],
rows: data.map((item) {
return FDataRow(
cells: [
FDataCell(Text(item['id'].toString())),
FDataCell(Text(item['name'])),
FDataCell(Text(item['age'].toString())),
],
);
}).toList(),
onFilter: (columnIndex, filterValue) {
print('Filtering column $columnIndex with value $filterValue');
},
)
6. 自定义样式
你可以通过 style
属性来自定义表格的样式:
FDataTable(
style: FDataTableStyle(
headerTextStyle: TextStyle(fontWeight: FontWeight.bold, color: Colors.blue),
rowColor: Colors.grey[200],
alternateRowColor: Colors.grey[100],
borderColor: Colors.grey,
borderWidth: 1.0,
),
columns: [
FDataColumn(label: Text('ID')),
FDataColumn(label: Text('Name')),
FDataColumn(label: Text('Age')),
],
rows: data.map((item) {
return FDataRow(
cells: [
FDataCell(Text(item['id'].toString())),
FDataCell(Text(item['name'])),
FDataCell(Text(item['age'].toString())),
],
);
}).toList(),
)