I am completely new to flutter and I am trying to make an application that has 7 switches for each day of the week.
The problem is resolved when a create 7 different switchlisttile with different values for each one.
But when I extracted the method, the switches don't work.
here is the code below:
Column(
children: <Widget>[
buildSwitchListTile(Title : "Monday" , Value : Value1),
buildSwitchListTile(Title : "Tuesday" , Value : Value2),
buildSwitchListTile(Title : "Wednesday" , Value : Value3),
buildSwitchListTile(Title : "Thursday" , Value : Value4),
buildSwitchListTile(Title : "Friday" , Value : Value5),
buildSwitchListTile(Title : "Saturday" , Value : Value6),
buildSwitchListTile(Title : "Sunday" , Value : Value7),
],
),
The extracted method:
SwitchListTile buildSwitchListTile({String Title , bool Value}) {
return SwitchListTile(
title: Text(Title),
value: Value1,
onChanged: (bool value) => setState(() {
Value1 = value;
}),
);
}
However I am aware that I have used Value1 in the method above, the reason is without it the switches don't work.
The problem is that the Value1
you pass into the method is not the same variable as the Value
that the method receives. They have the same value, but if you reassign a value to Value
, that will not affect the value of Value1
. You can instead hard-code Value1
like you are doing, but that would mean you need a method for each value
variable you have, which is not very DRY.
Instead, pass a callback method in for the buildSwitchListTile
to call when the tile gets tapped. That way, when you are calling that method in your build
method, you can specify which variable each one will change. After that, the program should run just fine.
SwitchListTile buildSwitchListTile({
String Title,
bool Value,
void Function(bool) onChanged,
}) {
return SwitchListTile(
title: Text(Title),
value: Value,
onChanged: onChanged,
);
}
And use it like this:
Column(
children: <Widget>[
buildSwitchListTile(Title: "Monday", Value: Value1,
onChanged: (val) => setState(() => Value1 = val)),
buildSwitchListTile(Title: "Tuesday", Value: Value2,
onChanged: (val) => setState(() => Value2 = val)),
buildSwitchListTile(Title: "Wednesday", Value: Value3,
onChanged: (val) => setState(() => Value3 = val)),
buildSwitchListTile(Title: "Thursday", Value: Value4,
onChanged: (val) => setState(() => Value4 = val)),
buildSwitchListTile(Title: "Friday", Value: Value5,
onChanged: (val) => setState(() => Value5 = val)),
buildSwitchListTile(Title: "Saturday", Value: Value6,
onChanged: (val) => setState(() => Value6 = val)),
buildSwitchListTile(Title: "Sunday", Value: Value7,
onChanged: (val) => setState(() => Value7 = val)),
],
),