You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Flutter中为SFDataGrid实现复选框及选中数据获取功能

为SFDataGrid添加复选框并实现选中数据展示

需求说明

已实现带数据的简单SFDataGrid,需添加复选框完成以下功能:

  • 选中行
  • 获取选中行的数据
  • 点击按钮展示选中的数据

解决方案

步骤1:添加DataGridController管理选中状态

在页面状态类中声明并初始化DataGridController,将其绑定到SfDataGrid组件,用于跟踪和获取选中行的索引。

步骤2:添加展示按钮与逻辑

在页面中添加按钮,点击时通过控制器获取选中行索引,映射为对应的业务数据对象后展示。

步骤3:完善数据源的原始数据映射

修改EmployeeDataSource,保存原始的Employee列表,方便通过选中行索引快速获取对应的数据对象,避免从表格行中逐个解析单元格内容。

修改后的完整代码

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

class CheckboxColumn extends StatefulWidget {
  const CheckboxColumn({Key? key}) : super(key: key);

  @override
  _CheckboxColumnState createState() => _CheckboxColumnState();
}

class _CheckboxColumnState extends State<CheckboxColumn> {
  late EmployeeDataSource _employeeDataSource;
  List<Employee> _employees = <Employee>[];
  // 声明DataGrid控制器,用于管理选中状态
  late DataGridController _dataGridController;

  @override
  void initState() {
    super.initState();
    _employees = getEmployeeData();
    _employeeDataSource = EmployeeDataSource(employees: _employees);
    _dataGridController = DataGridController();
  }

  // 处理选中数据展示逻辑
  void _showSelectedEmployees() {
    final selectedIndices = _dataGridController.selectedRows;
    if (selectedIndices.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('未选中任何行')),
      );
      return;
    }
    // 通过索引获取选中的员工数据
    final selectedEmployees = selectedIndices
        .map((index) => _employeeDataSource.employees[index])
        .toList();
    // 弹窗展示选中数据
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选中的员工'),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: selectedEmployees
                .map((emp) => Padding(
                      padding: const EdgeInsets.symmetric(vertical: 4.0),
                      child: Text(
                          'ID: ${emp.id}, 姓名: ${emp.name}, 职位: ${emp.designation}, 薪资: ${emp.salary}'),
                    ))
                .toList(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Syncfusion Flutter DataGrid')),
      body: Column(
        children: [
          // 顶部操作按钮
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: ElevatedButton(
              onPressed: _showSelectedEmployees,
              child: const Text('查看选中的数据'),
            ),
          ),
          // 数据表格区域
          Expanded(
            child: SfDataGrid(
              controller: _dataGridController, // 绑定控制器
              source: _employeeDataSource,
              showCheckboxColumn: true,
              checkboxColumnSettings: const DataGridCheckboxColumnSettings(
                backgroundColor: Color.fromARGB(255, 212, 0, 0),
              ),
              selectionMode: SelectionMode.multiple,
              columnWidthMode: ColumnWidthMode.fill,
              columns: <GridColumn>[
                GridColumn(
                    columnName: 'id',
                    label: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16.0),
                        alignment: Alignment.centerRight,
                        child: const Text('ID'))),
                GridColumn(
                    columnName: 'name',
                    label: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16.0),
                        alignment: Alignment.centerLeft,
                        child: const Text('姓名'))),
                GridColumn(
                    columnName: 'designation',
                    label: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16.0),
                        alignment: Alignment.centerLeft,
                        child: const Text('职位', overflow: TextOverflow.ellipsis))),
                GridColumn(
                    columnName: 'salary',
                    label: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16.0),
                        alignment: Alignment.centerRight,
                        child: const Text('薪资')))
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class EmployeeDataSource extends DataGridSource {
  EmployeeDataSource({required List<Employee> employees}) {
    this.employees = employees;
    dataGridRows = employees
        .map<DataGridRow>((employee) => DataGridRow(cells: [
              DataGridCell<int>(columnName: 'id', value: employee.id),
              DataGridCell<String>(columnName: 'name', value: employee.name),
              DataGridCell<String>(
                  columnName: 'designation', value: employee.designation),
              DataGridCell<int>(
                  columnName: 'salary', value: employee.salary),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];
  // 保存原始员工列表,用于快速映射选中行
  late List<Employee> employees;

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((dataGridCell) {
      return Container(
          alignment: (dataGridCell.columnName == 'id' ||
                  dataGridCell.columnName == 'salary')
              ? Alignment.centerRight
              : Alignment.centerLeft,
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Text(
            dataGridCell.value.toString(),
            overflow: TextOverflow.ellipsis,
          ));
    }).toList());
  }
}

class Employee {
  Employee(this.id, this.name, this.designation, this.salary);
  int id;
  String name;
  String designation;
  int salary;
}

List<Employee> getEmployeeData() {
  return [
    Employee(10001, 'James', '项目负责人', 20000),
    Employee(10002, 'Kathryn', '经理', 30000),
    Employee(10003, 'Lara', '开发工程师', 15000),
    Employee(10004, 'Michael', '设计师', 10000),
    Employee(10005, 'Martin', '开发工程师', 20000),
    Employee(10006, 'Newberry', '经理', 25000),
    Employee(10007, 'Balnc', '开发工程师', 35000),
    Employee(10008, 'Perry', '设计师', 45000),
    Employee(10009, 'Gable', '开发工程师', 10000),
    Employee(10010, 'Grimes', '开发工程师', 30000),
  ];
}

关键说明

  • DataGridController是Syncfusion DataGrid管理行选中状态的核心类,通过selectedRows属性可直接获取选中行的索引集合。
  • 在数据源中保留原始业务数据列表,能避免从表格行单元格中逐个解析数据的繁琐操作,提升代码可读性和效率。
  • 展示逻辑可根据需求调整,示例中使用弹窗展示,也可替换为SnackBar、新页面列表等形式。

内容的提问来源于stack exchange,提问作者Ant3xes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:54:56