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

Flutter DataGrid每行按钮切换对应行布尔值状态实现咨询

Flutter DataGrid 行按钮状态切换实现方案

现有代码问题

  • 按钮onPressed回调内仅写了未被渲染的Text组件,没有实际状态修改逻辑
  • 状态修改后没有触发数据源刷新通知,表格不会自动重绘
  • 未同步更新原始数据列表与DataGrid单元格存储的状态值,修改无法持久生效
  • 按钮文本固定写死,无法直观展示当前状态

核心实现逻辑

点击按钮时按以下流程处理即可实现预期效果:

  1. 定位当前点击行对应的原始数据模型
  2. 将模型中绑定的布尔值取反
  3. 同步更新DataGrid对应单元格存储的状态值
  4. 调用notifyListeners()通知DataGrid重绘行内容

可直接复用的修改代码

替换你原有第6列(状态按钮列)的Container代码即可:

Container(
  margin: EdgeInsets.only(bottom: 20.0),
  decoration: BoxDecoration(
    // 状态不同显示不同按钮颜色,交互更直观
    color: row.getCells()[5].value == false ? Colors.blue : Colors.green,
    borderRadius: BorderRadius.circular(15.0)
  ),
  child: Center(
    // 原FlatButton已在Flutter 2.0+版本废弃,替换为官方推荐的TextButton
    child: TextButton(
      onPressed: () {
        // 无排序/过滤场景下,DataGrid行与原始列表索引一一对应,直接取索引即可
        final rowIndex = dataGridRows.indexOf(row);
        // 1. 更新原始数据源的布尔状态
        list[rowIndex].isSelected = !list[rowIndex].isSelected;
        // 2. 同步更新DataGrid单元格存储的状态值
        dataGridRows[rowIndex].getCells()[5] = DataGridCell<bool>(
          columnName: 'الحاله',
          value: list[rowIndex].isSelected
        );
        // 3. 通知表格刷新UI
        notifyListeners();

        // 如需调用API提交状态,在这里加接口请求逻辑即可
        // 例:await updateStatusApi(list[rowIndex].iD, list[rowIndex].isSelected);
      },
      child: Center(
        child: Text(
          // 按状态显示对应按钮文本,可自行替换为阿拉伯语文案
          row.getCells()[5].value == false ? '标记为已处理' : '已处理',
          style: TextStyle(fontSize: 15, color: Colors.white),
        ),
      ),
    ),
  ),
)

兼容排序/过滤场景的适配方案

如果你给DataGrid配置了排序、过滤功能,行索引会和原始列表错位,需要用唯一ID匹配数据,将onPressed内逻辑替换为以下代码即可:

onPressed: () {
  // 获取当前行的唯一操作ID
  final currentOpId = row.getCells()[3].value as int;
  // 匹配原始数据列表中的对应项
  final modelIndex = list.indexWhere((item) => item.iD == currentOpId);
  // 匹配当前显示的DataGrid行索引
  final gridRowIndex = dataGridRows.indexWhere((gridRow) => gridRow.getCells()[3].value == currentOpId);
  
  // 更新状态
  list[modelIndex].isSelected = !list[modelIndex].isSelected;
  dataGridRows[gridRowIndex].getCells()[5] = DataGridCell<bool>(
    columnName: 'الحاله',
    value: list[modelIndex].isSelected
  );
  notifyListeners();
}

内容的提问来源于stack exchange,提问作者Faith.youssef.abk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 03:06:11