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

如何通过点击Button为SFDataGrid组件动态添加数据行

SfDataGrid 点击按钮新增行实现方案

核心实现逻辑

Syncfusion Flutter DataGrid 不会自动监听数据集合变更,需要通过 DataGridSource 提供的 notifyListeners() 方法主动通知表格刷新数据。你只需要修改两处代码即可实现需求:

1. 扩展 EmployeeDataSource 类,新增数据插入方法

在现有 EmployeeDataSource 类中新增 addEmployee 方法,用于接收新的员工数据,转换为 DataGridRow 后插入内部集合,最后触发刷新通知:

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

  List<DataGridRow> _employeeData = [];

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

  // 新增的插入数据方法
  void addEmployee(Employee employee) {
    _employeeData.add(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),
    ]));
    // 通知DataGrid刷新UI
    notifyListeners();
  }

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((e) {
          return Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(8.0),
            child: Text(e.value.toString()),
          );
        }).toList());
  }
}

2. 补充 MaterialButton 的点击事件逻辑

在按钮的 onPressed 回调中构造硬编码的员工数据,调用刚才新增的 addEmployee 方法即可完成新增:

MaterialButton(
  color: Colors.red,
  onPressed: () {
    // 硬编码新增的员工数据,可按需修改字段值
    final newEmployee = Employee(20203, '张三', '产品经理', 25000);
    employeeDataSource.addEmployee(newEmployee);
  },
  child: const Text('新增一行', style: TextStyle(color: Colors.white)),
)

修改完成后点击按钮即可看到新行自动追加到表格末尾,无需额外调用 setState 刷新整个页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:24:01