Flutter数据表格展示插件bs_flutter_datatable_2的使用

Flutter数据表格展示插件bs_flutter_datatable_2的使用

bs_flutter_datatable_2 是一个简单的方式来展示通过服务器端处理的数据。它支持自定义样式、搜索功能、分页、每页长度、排序和服务器端处理等功能。

功能

  • 自定义样式
  • 可搜索数据
  • 分页
  • 每页长度
  • 排序
  • 服务器端处理

开始使用

pubspec.yaml 文件中添加依赖:

dependencies:
  ...
  bs_flutter_datatable_2: any

数据表格

示例代码位于 main.dart

要创建一个数据表格,你需要导入以下包:

import 'package:bs_flutter_datatable_2/bs_flutter_datatable.dart';

创建数据源

class ExampleSource extends BsDatatableSource {
  static List<BsDataColumn> get columns => [
    BsDataColumn(label: Text('No'), orderable: false, searchable: false, width: 100.0),
    BsDataColumn(label: Text('Code'), columnName: 'typecd', width: 200.0),
    BsDataColumn(label: Text('Name'), columnName: 'typenm'),
  ];

  @override
  BsDataRow getRow(int index) {
    return BsDataRow(index: index, cells: [
      BsDataCell(Text('${controller.start + index + 1}')),
      BsDataCell(Text('${response.data[index]['typecd']}')),
      BsDataCell(Text('${response.data[index]['typenm']}')),
    ]);
  }
}

添加行事件监听器

class ExampleSource extends BsDatatableSource {
  ValueChanged<dynamic> onEditListener = (value) {};
  ValueChanged<dynamic> onDeleteListener = (value) {};

  @override
  BsDataRow getRow(int index) {
    return BsDataRow(index: index, cells: [
      BsDataCell(Row(
        children: [
          TextButton(
            onPressed: () => onEditListener(response.data[index]['typeid']), 
            child: Container(child: Text('Edit'))
          ),
          TextButton(
            onPressed: () => onDeleteListener(response.data[index]['typeid']),
            child: Container(child: Text('Delete'))
          )
        ],
      ))
    ]);
  }
}

处理事件

在请求数据成功后更新事件处理器:

Future loadApi(Map<String, dynamic> params) {
  return http.post(
    Uri.parse('http://localhost/flutter_crud/api/public/types/datatables'),
    body: params,
  ).then((value) {
    Map<String, dynamic> json = jsonDecode(value.body);
    setState(() {
      _source.response = BsDatatableResponse.createFromJson(json['data']);
      _source.onEditListener = (typeid) {
        /// 执行编辑操作
      };
      _source.onDeleteListener = (typeid) {
        /// 执行删除操作
      };
    });
  });
}

声明数据源和控制器

class _MyAppState extends State<MyApp> {
  ExampleSource _source = ExampleSource();

  @override
  void initState() {
    _source.controller = BsDatatableController();
    super.initState();
  }

  // 其他代码...
}

创建表格视图

BsDatatable(
  source: _source,
  title: Text('Datatables Data'),
  columns: ExampleSource.columns,
  serverSide: loadApi,
)

服务器端函数

Future loadApi(Map<String, dynamic> params) {
  return http.post(
    Uri.parse('http://localhost/flutter_crud/api/public/types/datatables'),
    body: params,
  ).then((value) {
    Map<String, dynamic> json = jsonDecode(value.body);
    setState(() {
      _source.response = BsDatatableResponse.createFromJson(json['data']);
      _source.onEditListener = (typeid) {
        /// 执行编辑操作
      };
      _source.onDeleteListener = (typeid) {
        /// 执行删除操作
      };
    });
  });
}

注意事项

在从服务器请求数据成功后,需要更新数据源的响应数据:

Future loadApi(Map<String, dynamic> params) {
  return http.post(
    // ...
  ).then((value) {
    // ...
    setState(() {
      _source.response = BsDatatableResponse.createFromJson(json['data']);
      // ...
    });
  });
}

重新加载数据

你可以使用 reload 函数来重新加载数据:

_source.controller.reload();

显示本地数据

如果想显示本地数据,可以在构造函数中传递 data 列表:

class ExampleSource extends BsDatatableSource {
  ExampleSource({List? data}) : super(data: data);
  // 其他代码...
}

然后在你的组件中设置数据源:

class Datatables extends StatefulWidget {
  @override
  _DatatablesState createState() => _DatatablesState();
}

class _DatatablesState extends State<Datatables> {
  ExampleSource _source1 = ExampleSource(
    data: [
      {'typecd': 'TP1', 'typenm': 'Type 1'},
      {'typecd': 'TP2', 'typenm': 'Type 2'},
      {'typecd': 'TP3', 'typenm': 'Type 3'},
      {'typecd': 'TP4', 'typenm': 'Type 4'},
      {'typecd': 'TP5', 'typenm': 'Type 5'},
    ]
  );

  // 其他代码...
}

动态添加数据

你可以使用 addaddAll 方法动态添加数据,使用 put 方法更新数据,使用 removeremoveAt 方法移除数据:

TextButton(
  onPressed: () {
    _source1.add({'typecd': 'TP1', 'typenm': 'Type ${_source1.datas.length}'});
  },
  child: Text('Add Row'),
)

更多关于Flutter数据表格展示插件bs_flutter_datatable_2的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据表格展示插件bs_flutter_datatable_2的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


bs_flutter_datatable_2 是一个用于在 Flutter 应用中展示数据表格的插件。它允许你以表格的形式展示数据,支持排序、分页、自定义样式等功能。以下是如何使用 bs_flutter_datatable_2 的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 bs_flutter_datatable_2 依赖:

dependencies:
  flutter:
    sdk: flutter
  bs_flutter_datatable_2: ^latest_version

然后运行 flutter pub get 来安装依赖。

2. 导入包

在你的 Dart 文件中导入 bs_flutter_datatable_2

import 'package:bs_flutter_datatable_2/bs_flutter_datatable_2.dart';

3. 创建数据表格

使用 BsDatatable 组件来创建数据表格。你需要提供表头和数据。

class DataTableExample extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DataTable Example'),
      ),
      body: SingleChildScrollView(
        child: BsDatatable(
          columns: [
            BsDataColumn(label: Text('ID')),
            BsDataColumn(label: Text('Name')),
            BsDataColumn(label: Text('Age')),
          ],
          rows: [
            BsDataRow(cells: [
              BsDataCell(Text('1')),
              BsDataCell(Text('John Doe')),
              BsDataCell(Text('25')),
            ]),
            BsDataRow(cells: [
              BsDataCell(Text('2')),
              BsDataCell(Text('Jane Smith')),
              BsDataCell(Text('30')),
            ]),
            BsDataRow(cells: [
              BsDataCell(Text('3')),
              BsDataCell(Text('Mike Johnson')),
              BsDataCell(Text('22')),
            ]),
          ],
        ),
      ),
    );
  }
}

4. 配置表格

BsDatatable 提供了许多配置选项,例如分页、排序、自定义样式等。

分页

你可以通过设置 pagination 属性来启用分页:

BsDatatable(
  pagination: BsPagination(
    currentPage: 1,
    totalPages: 10,
    onPageChanged: (page) {
      // Handle page change
    },
  ),
  // Other properties...
)

排序

你可以通过设置 sortable 属性来启用排序:

BsDatatable(
  sortable: true,
  onSort: (columnIndex, sortDirection) {
    // Handle sort
  },
  // Other properties...
)

自定义样式

你可以通过设置 style 属性来自定义表格样式:

BsDatatable(
  style: BsTableStyle(
    headerColor: Colors.blue,
    rowColor: Colors.white,
    hoverColor: Colors.grey[200],
  ),
  // Other properties...
)

5. 运行应用

现在你可以运行你的 Flutter 应用,并查看数据表格的效果。

完整示例

以下是一个完整的示例,展示了如何使用 bs_flutter_datatable_2

import 'package:flutter/material.dart';
import 'package:bs_flutter_datatable_2/bs_flutter_datatable_2.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter DataTable Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: DataTableExample(),
    );
  }
}

class DataTableExample extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DataTable Example'),
      ),
      body: SingleChildScrollView(
        child: BsDatatable(
          columns: [
            BsDataColumn(label: Text('ID')),
            BsDataColumn(label: Text('Name')),
            BsDataColumn(label: Text('Age')),
          ],
          rows: [
            BsDataRow(cells: [
              BsDataCell(Text('1')),
              BsDataCell(Text('John Doe')),
              BsDataCell(Text('25')),
            ]),
            BsDataRow(cells: [
              BsDataCell(Text('2')),
              BsDataCell(Text('Jane Smith')),
              BsDataCell(Text('30')),
            ]),
            BsDataRow(cells: [
              BsDataCell(Text('3')),
              BsDataCell(Text('Mike Johnson')),
              BsDataCell(Text('22')),
            ]),
          ],
          pagination: BsPagination(
            currentPage: 1,
            totalPages: 10,
            onPageChanged: (page) {
              // Handle page change
            },
          ),
          sortable: true,
          onSort: (columnIndex, sortDirection) {
            // Handle sort
          },
          style: BsTableStyle(
            headerColor: Colors.blue,
            rowColor: Colors.white,
            hoverColor: Colors.grey[200],
          ),
        ),
      ),
    );
  }
}
回到顶部