首页 > 解决方案 > 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.

标签: flutterdart

解决方案


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))
    ],
  ),
);
}

推荐阅读