How to Change Row Colors Dynamically by Theme in Flutter DataTable?
In this article, we will show you how to dynamically change row colors based on the theme in Flutter DataTable.
Initialize the SfDataGrid widget with all the necessary properties. To achieve this, set the appropriate context to the DataGridSource.context
property and call notifyListeners from the DataGridSource when the theme is changed.
Brightness brightness = Brightness.light;
@override
Widget build(BuildContext context) {
return Theme(
data: ThemeData(brightness: brightness),
child: Scaffold(
appBar: AppBar(title: const Text('Syncfusion Flutter DataGrid')),
body: Builder(builder: (context) {
return Column(
children: [
ElevatedButton(
onPressed: (() {
setState(() {
if (brightness == Brightness.dark) {
brightness = Brightness.light;
_employeeDataSource.context = context;
} else {
brightness = Brightness.dark;
_employeeDataSource.context = context;
}
});
_employeeDataSource.updateDataGrid();
}),
child: const Text('Change Theme')),
const Padding(padding: EdgeInsets.all(5)),
Expanded(
child: SfDataGrid(
source: _employeeDataSource,
columns: getColumns,
columnWidthMode: ColumnWidthMode.fill,
),
),
],
);
})),
);
}
class EmployeeDataSource extends DataGridSource {
…
BuildContext context;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
color: Theme.of(context).brightness == Brightness.light
? Colors.teal
: Colors.deepOrangeAccent,
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
void updateDataGrid() {
notifyListeners();
}
}
You can download the example from GitHub.
Conclusion
I hope you enjoyed learning how to change row colors dynamically by theme in Flutter DataTable.
You can refer to our Flutter DataGrid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Flatter DataGrid example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!