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

Flutter PlutoGrid组件如何设置整行聚焦而非单个单元格?

PlutoGrid 整行聚焦实现方案(v8.0.0)

PlutoGrid 暂无直接配置整行聚焦的官方选项,但可以通过以下两种方式实现你的需求:

一、键盘事件拦截 + 整行激活高亮

  1. 禁用左右方向键:拦截默认的单元格切换逻辑,让左右键失效
  2. 自定义上下键行为:通过上下键切换整行的激活状态,同时区分激活(聚焦)与选中状态

示例代码:

PlutoGrid(
  columns: yourColumns,
  rows: yourRows,
  configuration: PlutoGridConfiguration(
    keyboard: PlutoGridKeyboardConfiguration(
      handleKeyEvent: (event, focusedCell, gridState) {
        // 拦截左右方向键,不执行默认单元格切换
        if (event.isKeyPressed(LogicalKeyboardKey.arrowLeft) ||
            event.isKeyPressed(LogicalKeyboardKey.arrowRight)) {
          return true;
        }
        // 处理上下键,切换整行激活状态
        if (event.isKeyPressed(LogicalKeyboardKey.arrowUp) ||
            event.isKeyPressed(LogicalKeyboardKey.arrowDown)) {
          final direction = event.isKeyPressed(LogicalKeyboardKey.arrowUp) 
              ? PlutoMoveDirection.up 
              : PlutoMoveDirection.down;
          final targetRow = gridState.currentRow?.move(direction, gridState.rows);
          if (targetRow != null) {
            gridState.setCurrentRow(targetRow, notify: true);
            gridState.setActivatedRow(targetRow); // 标记整行为激活状态
          }
          return true;
        }
        return false;
      },
    ),
    // 自定义行样式,区分激活与选中状态
    rowColorCallback: (rowIndex, row) {
      if (row == gridState.currentState?.activatedRow) {
        return Colors.blue.withOpacity(0.1); // 整行激活高亮
      }
      if (row.selected) {
        return Colors.grey.withOpacity(0.1); // 选中行样式
      }
      return null;
    },
  ),
)

二、自定义单元格组件,隐藏单个单元格焦点

如果需要彻底隐藏单个单元格的焦点视觉效果,可以自定义单元格渲染组件,基于行激活状态统一高亮:

PlutoColumn(
  title: '示例列',
  field: 'example',
  renderer: (rendererContext) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      color: rendererContext.row == rendererContext.state.activatedRow 
          ? Colors.blue.withOpacity(0.1) 
          : null,
      child: Text(rendererContext.cell.value.toString()),
    );
  },
)

核心注意点

  • 激活(聚焦)状态通过 gridState.setActivatedRow() 控制,选中状态通过 gridState.toggleSelectRow() 控制,二者完全独立
  • 测试时需确保 PlutoGrid 获得焦点,避免键盘事件被外部组件拦截

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:32:40