How to Delete Rows using Button in Flutter DataTable (SfDataGrid)?
In this article, we will show you how to delete selected rows using delete button in Flutter DataTable.
Initialize the SfDataGrid widget with all the required properties. In the buildRow method, display the Details
and Delete
buttons based on row selection using the selectedRows list from the DataGridController. When a row is selected, the delete button will appear in the last column. Tapping the delete button removes the corresponding row from DataGridSource.rows, and calling notifyListeners() refreshes the SfDataGrid to reflect the changes.
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
bool isSelected = controller.selectedRows.contains(row);
return DataGridRowAdapter(
cells:
row.getCells().map<Widget>((dataGridCell) {
if (dataGridCell.columnName == 'button') {
return Padding(
padding: const EdgeInsets.all(3.0),
child: ElevatedButton(
onPressed: () {
if (isSelected) {
dataGridRow.remove(row);
notifyListeners();
} else {
showDialog(
context: context,
builder:
(context) => AlertDialog(
title: Text('Employee Details'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'ID: ${row.getCells()[0].value.toString()}',
),
Text(
'Name: ${row.getCells()[1].value.toString()}',
),
Text(
'Designation: ${row.getCells()[2].value.toString()}',
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Close'),
),
],
),
);
}
},
style: ElevatedButton.styleFrom(
backgroundColor: isSelected ? Colors.red : Colors.blue,
),
child:
isSelected
? const Icon(Icons.delete, color: Colors.white)
: const Text('Details'),
),
);
}
return Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8.0),
child: Text(dataGridCell.value.toString()),
);
}).toList(),
);
}
You can download this example on GitHub.
Conclusion
I hope you enjoyed learning how to delete rows using button in Flutter DataTable (SfDataGrid).
You can refer to our Flutter Datatable 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 Datatable (sfDataGrid) 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!