I am new Flutter and I am facing a problem and I have no idea why.
In Below code when choose value from DropDown it change value of "selectedMonths" But when i select DataRow it uses the default value "1". Please anyone help me with this.
vehicleFeeData(List<VehicleFee>? list) {
return Padding(
padding: EdgeInsets.fromLTRB(0, 0, 0, 10),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
showCheckboxColumn: true,
headingRowColor: MaterialStateProperty.all(Colors.yellow[50]),
border: TableBorder.all(color: Colors.grey[200]!),
columnSpacing: 20,
columns: [
DataColumn(label: Text('Plate Number')),
DataColumn(label: Text('Exp Date')),
DataColumn(label: Text('Monthly Fee')),
DataColumn(label: Text('Months')),
],
rows: list!.map((fee) {
int selectedMonths = 1; // This value
return DataRow(
selected: vehiclesFee!.contains(fee),
onSelectChanged: (selected) {
if (vehiclesFee!.contains(fee)) {
state!(() {
print(selectedMonths);
vehiclesFee!.remove(fee);
vehiclesFeeTotal -=
(int.parse(fee.monthlyFee!) * selectedMonths);
});
} else {
state!(() {
print(selectedMonths);
vehiclesFee!.add(fee);
vehiclesFeeTotal =
(int.parse(fee.monthlyFee!) * selectedMonths);
});
}
},
cells: [
DataCell(Text(fee.plateNumber!)),
DataCell(Text(fee.expDate!.toString().split('00').first)),
DataCell(Text(fee.monthlyFee!)),
DataCell(Container(
width: getProportionateScreenWidth(135),
child: DropdownButtonFormField(
onChanged: (value) {
state!(() {
selectedMonths = int.parse(value.toString());
print(selectedMonths);
});
},
decoration: InputDecoration(
contentPadding:
EdgeInsets.symmetric(horizontal: 5, vertical: 5),
border: border,
enabledBorder: border,
errorBorder: border,
focusedBorder: border,
focusedErrorBorder: border,
hintText: "Select Months",
),
items: popUpMenuItem,
),
)),
]);
}).toList(),
),
));
}
CodePudding user response:
you missed to use value
in dropdown
DropdownButtonFormField(
onChanged: (value) {
state!(() {
selectedMonths = int.parse(value.toString());
print(selectedMonths);
});
},
value: selectedMonths, // here need to change
decoration: InputDecoration(
contentPadding:
EdgeInsets.symmetric(horizontal: 5, vertical: 5),
border: border,
enabledBorder: border,
errorBorder: border,
focusedBorder: border,
focusedErrorBorder: border,
hintText: "Select Months",
),
items: popUpMenuItem,
),
CodePudding user response:
You should declare int selectedMonths = 1;
outside the build method because when you call !state
and the widget rebuild, selectedMonths
's value initializes to 1 again.