I have a DataTable in my scene. I want to change the background color of rows when the user hovers over any row. I found several samples on flutter.dev but none are working.
For instance, look at the following code (full code). Although I have green as the background color, it doesn't turn into blue when I hover over the rows.
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;
}
}