How to Enable Column Resizing and Drag-and-Drop in Flutter DataTable?
In this article, we will show you how to enable both column resizing and drag-and-drop in Flutter DataTable.
Initialize the SfDataGrid widget with all the required properties. Maintain the column width collection at the application level and use the SfDataGrid.onColumnResizeUpdate callback to update the column width for the corresponding column. To reorder the columns in the DataGrid, create an instance to hold the columns and assign it to the SfDataGrid.columns property, instead of directly assigning the list of GridColumn. When resizing, create a new GridColumn instance with the updated width value and replace the existing column in the list.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
allowColumnsResizing: true,
onColumnResizeUpdate: (ColumnResizeUpdateDetails details) {
setState(() {
int index = getDataGridColumns.indexOf(
getDataGridColumns.firstWhere((element) =>
element.columnName == details.column.columnName));
getDataGridColumns[index] = GridColumn(
columnName: details.column.columnName,
width: details.width,
label: details.column.label);
});
return true;
},
allowColumnsDragging: true,
columns: getDataGridColumns,
onColumnDragging: (DataGridColumnDragDetails details) {
if (details.action == DataGridColumnDragAction.dropped &&
details.to != null) {
final GridColumn rearrangeColumn =
getDataGridColumns[details.from];
getDataGridColumns.removeAt(details.from);
getDataGridColumns.insert(details.to!, rearrangeColumn);
_employeeDataSource.buildDataGridRows();
_employeeDataSource.refreshDataGrid();
}
return true;
},
),
),
);
}
You can download this example on GitHub.
I hope you enjoyed learning how to enable column resizing and drag-and-drop 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 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!