如何在将鼠标悬停在行上时更改 Flutter DataTable 的背景颜色?

Hes*_*sam 9 flutter flutter-datatable

我的场景中有一个数据表。我想当用户将鼠标悬停在任何行上时更改行的背景颜色。我在 flutter.dev 上找到了几个示例,但没有一个有效。

例如,看下面的代码(完整代码)。虽然我将绿色作为背景颜色,但当我将鼠标悬停在行上时,它不会变成蓝色。

class MyStatelessWidget extends StatelessWidget {
  const MyStatelessWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DataTable(
      dataRowColor: MaterialStateProperty.resolveWith(_getDataRowColor),
      columns: const <DataColumn>[
        DataColumn(
          label: Text(
            'Name',
            style: TextStyle(fontStyle: FontStyle.italic),
          ),
        ),
        DataColumn(
          label: Text(
            'Age',
            style: TextStyle(fontStyle: FontStyle.italic),
          ),
        ),
        DataColumn(
          label: Text(
            'Role',
            style: TextStyle(fontStyle: FontStyle.italic),
          ),
        ),
      ],
      rows: <DataRow>[
        DataRow(
          cells: <DataCell>[
            DataCell(Text('Sarah')),
            DataCell(Text('19')),
            DataCell(Text('Student')),
          ],
          onSelectChanged: (isSelected) => {
            print('Item 1 clicked!')
          },
        ),
        DataRow(
          cells: <DataCell>[
            DataCell(Text('Janine')),
            DataCell(Text('43')),
            DataCell(Text('Professor')),
          ],
          onSelectChanged: (isSelected) => {
            print('Item 2 clicked!')
          },
        ),
        DataRow(
          cells: <DataCell>[
            DataCell(Text('William')),
            DataCell(Text('27')),
            DataCell(Text('Associate Professor')),
          ],
          onSelectChanged: (isSelected) => {
            print('Item 3 clicked!')
          },
        ),
      ],
    );
  }

  Color _getDataRowColor(Set<MaterialState> states) {
    const Set<MaterialState> interactiveStates = <MaterialState>{
      MaterialState.pressed,
      MaterialState.hovered,
      MaterialState.focused,
    };

    if (states.any(interactiveStates.contains)) {
      return Colors.blue;
    }
    return Colors.green;
  }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Hes*_*sam 3

我发现问题出在哪里了。以下代码修复了我在问题中提出的悬停在行上的问题。但是,默认情况下为所有行设置透明背景是我的解决方案的代价。

Color _getDataRowColor(Set<MaterialState> states) {
    const Set<MaterialState> interactiveStates = <MaterialState>{
      MaterialState.pressed,
      MaterialState.hovered,
      MaterialState.focused,
    };

    if (states.any(interactiveStates.contains)) {
      return Colors.blue;
    }
    //return Colors.green; // Use the default value.
    return Colors.transparent;
  }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述