What is the correct way to Setstate of checkboxListTile to get both toggle button and added value to it?
What I want is when you check the box, You see the check button. then the value added into the base price. Please kindly help.
CheckboxListTile(
activeColor: Colors.blue,
dense: true,
//font change
title: new Text(
listTopping[i].price.toStringAsFixed(0) +
' บาท',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
value: listTopping[i].isCheck,
secondary: Container(
height: 50,
width: 300,
child: Text(
listTopping[i].topping,
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
),
onChanged: (bool? val) {
itemChange(val!, i);
},
),
Here is the setstate that I believe is wrong...
void itemChange(bool val, int i) {
setState(() {
listTopping[i].isCheck = val;
});
}
}
Here is a small example of your code. Since you didn't provide the AddonTopping
class I created a simply version for myself. You can try it out and run this Widget in your MaterialApp
. Everything should worked as expected.
class AddonTopping {
AddonTopping({
required this.id,
required this.topping,
required this.isCheck,
required this.price,
});
final int id;
final String topping;
bool isCheck;
final int price;
}
class Americano extends StatefulWidget {
@override
_AmericanoState createState() => _AmericanoState();
}
class _AmericanoState extends State<Americano> {
List<AddonTopping> listTopping = [
AddonTopping(
id: 8,
topping: 'Whipcream',
price: 0,
isCheck: true,
),
AddonTopping(
id: 9,
topping: 'Javachip',
price: 30,
isCheck: false,
),
AddonTopping(
id: 10,
topping: 'SoyMilk',
price: 20,
isCheck: false,
),
AddonTopping(
id: 11,
topping: 'ExtraSyrup',
price: 30,
isCheck: false,
),
];
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('SUM: ${calculatePrice()}'),
ListView.builder(
shrinkWrap: true,
itemCount: listTopping.length,
itemBuilder: (context, i) => CheckboxListTile(
activeColor: Colors.blue,
dense: true,
//font change
title: Text(
listTopping[i].price.toStringAsFixed(0),
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
value: listTopping[i].isCheck,
secondary: Container(
height: 50,
width: 300,
child: Text(
listTopping[i].topping,
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
),
onChanged: (bool? val) {
itemChange(val!, i);
},
),
),
],
);
}
void itemChange(bool val, int i) {
setState(() {
listTopping[i].isCheck = val;
});
}
double calculatePrice() {
if (listTopping.isNotEmpty) {
double _price = 0.0;
// Get those toppings that are chosen (`isCheck` is true)
final chosenTopping = listTopping.where((element) => element.isCheck);
// Calculate the sum
for (final AddonTopping item in chosenTopping) {
if (item.isCheck) {
_price += item.price;
}
}
return _price;
}
return 0.00;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.