Mateus Félix
Mateus Félix

Reputation: 37

Flutter - Switch inside a Widget Function not updating

I have this Widget function:

Widget setDayOpen(String weekDay, bool state) {
  return Container(
    padding: EdgeInsets.only(right: 10, left: 10),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(weekDay,
          style: TextStyle(
            fontFamily: 'RobotoCondensed',
            fontSize: 20,
            fontWeight: FontWeight.bold,
          )),
        Switch(
          value: state,
          onChanged: (s) {
            setState(() {
              state = s;
              print(state);
            });
          })
      ],
    ),
  );
}

The android emulator has building the widget correctly (with the Day Week text and a Swicth side by side), but when i press the switch, the print only returns "true" and the Switch dont move. What is wrong here? I declared the value bool = false before inserting it into the function.

Upvotes: 0

Views: 1584

Answers (2)

Anirudh Sharma
Anirudh Sharma

Reputation: 727

You should create a callback function and pass it, if you want to access the variables present inside you widget. For example

setDayOpen("Tuesday",state,(s) {
            setState(() {
              state = s;
              print(state);
            });
          })

Widget setDayOpen(String weekDay, bool state, Function callBack) {

return Container(
  padding: EdgeInsets.only(right: 10, left: 10),
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
      Text(weekDay,
          style: TextStyle(
            fontFamily: 'RobotoCondensed',
            fontSize: 20,
            fontWeight: FontWeight.bold,
          )),
      Switch(
          value: state,
          onChanged: (s)=>callBack(s))
    ],
  ),
);
}

Upvotes: 1

F Perroch
F Perroch

Reputation: 2225

You have to change the value of the state variable with the setState() method like you do but you have to ensure that the widget is rebuilt with the new state value.

In order, the Switch widget doesn't update when it's value don't change

Upvotes: 0

Related Questions