Category / Section
How to change the Flutter DataTable's column width?
3 mins read
The Flutter DataTable (Data Grid) widget provides support to change the width of the column by setting the required value to width property in GridColumn.
STEP 1: Create data source class extends with DataGridSource for mapping data to the SfDataGrid.
class EmployeeDataSource extends DataGridSource { EmployeeDataSource({required List<Employee> employeeData}) { _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(); } List<DataGridRow> _employeeData = []; @override List<DataGridRow> get rows => _employeeData; @override DataGridRowAdapter buildRow(DataGridRow row) { return DataGridRowAdapter( cells: row.getCells().map<Widget>((e) { return Container( alignment: Alignment.center, padding: EdgeInsets.symmetric(horizontal: 16), child: Text(e.value.toString()), ); }).toList()); } }
STEP 2: Initialize the SfDataGrid with all the required properties. Provide the value for width property, which is available in the GridColumn. By default, the column width is 90 for the android and the iOS platforms, whereas the column width is 100 for the desktop platforms. If zero is set to this property, then the column will not show in view.
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Syncfusion Flutter DataGrid'), ), body: SfDataGrid( source: employeeDataSource, columns: <GridColumn>[ GridColumn( columnName: 'id', width: 60, label: Container( padding: EdgeInsets.symmetric(horizontal: 16), alignment: Alignment.center, child: Text( 'ID', ))), GridColumn( columnName: 'name', width: 100, label: Container( padding: EdgeInsets.symmetric(horizontal: 16), alignment: Alignment.center, child: Text('Name'))), GridColumn ( columnName: 'designation', width: 150, label: Container( padding: EdgeInsets.symmetric(horizontal: 16), alignment: Alignment.center, child: Text( 'Designation', overflow: TextOverflow.ellipsis, ))), GridColumn ( columnName: 'salary', width: 100, label: Container( padding: EdgeInsets.symmetric(horizontal: 16), alignment: Alignment.center, child: Text('Salary'))), ], ), ); }
Note
Use the columnWidthMode property to show the columns based on certain logics. Refer this UG link for more information.