问题
I'm trying to delete a selected row from a DataTable by retrieving the value of the first cell (id) and passing it to the deleteRow function. How do I get this value?
child: DataTable(
columns: data.first.keys
.map((dynamic keys) => DataColumn(label: Text(keys.toString())))
.toList(),
rows: data.map((map) {
return DataRow(
onSelectChanged: (bool selected) {
if (selected) {
try {
//determine the id of the selected row
int selectedId = /*get index of selected row and return value of the first cell*/
//delete row associated with id in db
deleteRow(selectedId);
//update ui to remove that row
setState(() {});
} catch (e) {
return SnackBar(
content: Text('Cant delete this row. EXCEPTION: $e'),
);
}
}
},
cells: map.values.map((dynamic val) => DataCell(Text(val.toString()))).toList());
}).toList()),
回答1:
List<Map> data = [], selected = [];
@override
void initState() {
super.initState();
data.add({'id': 'Emp1', 'name': 'Naveen', 'salary': 50000});
data.add({'id': 'Emp3', 'name': 'Satish', 'salary': 35000});
data.add({'id': 'Emp2', 'name': 'Ram', 'salary': 40000});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.all(15),
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
selected.length < 1
? 'Nothing Selected !'
: 'First cell : ${selected[0].values.toList()[0]}',
textAlign: TextAlign.center),
DataTable(
columns: data.first.keys
.map((dynamic keys) =>
DataColumn(label: Text(keys.toString())))
.toList(),
rows: data.map((map) {
return DataRow(
selected: selected.contains(map),
onSelectChanged: (boo) {
if (boo) {
setState(() {
selected.add(map);
});
} else {
setState(() {
selected.remove(map);
});
}
},
cells: map.values.map((value) {
return DataCell(Text(value.toString()));
}).toList());
}).toList()),
],
),
));
}
来源:https://stackoverflow.com/questions/59781177/datatable-get-the-value-of-the-first-cell-from-a-selected-row