How to Get the BuildContext in the Source of Flutter DataGrid?
In this article, we will show you how to get the BuildContext in the DataGridSource of Flutter DataGrid.
Initialize the SfDataGrid widget with all the necessary properties. You can achieve this by maintaining the build context in the DataGridSource. In the initState method, pass the context to the DataGridSource so that you can access the BuildContext within the DataGridSource.
List<Employee> employees = <Employee>[];
late EmployeeDataSource employeeDataSource;
@override
void initState() {
super.initState();
employees = getEmployeeData();
employeeDataSource = EmployeeDataSource(employees, context);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Syncfusion Flutter DataGrid'),
),
body: SfDataGrid(
source: employeeDataSource,
columnWidthMode: ColumnWidthMode.fill,
columns: getColumns
),
);
}
class EmployeeDataSource extends DataGridSource {
/// Creates the employee data source class with required details.
EmployeeDataSource(List<Employee> employeeData, this.context) {
_employeeData = employeeData
.map<DataGridRow>((e) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: e.id),
DataGridCell<String>(columnName: 'name', value: e.name),
DataGridCell<String>(
columnName: 'designation', value: e.designation),
DataGridCell<int>(columnName: 'salary', value: e.salary),
]))
.toList();
}
BuildContext context;
@override
DataGridRowAdapter buildRow(DataGridRow row) {
return DataGridRowAdapter(
color: Theme.of(context).primaryColor,
cells: row.getCells().map<Widget>((e) {
return Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8.0),
child: Text(e.value.toString()),
);
}).toList());
}
}
You can download this example on GitHub.
Conclusion
I hope you enjoyed learning how to get the build context in the source of Flutter DataGrid.
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 Flutter 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!