flutter - 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.
解决方案
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))
],
),
);
}
推荐阅读
- r - 如何在R中将网络分割成相等的线段
- reactjs - 用于 safari 和 firefox 的 textarea 中的多行占位符
- c - 在 c 中使用 fscanf() 从 json 文件中读取
- javascript - 无法选择任何项目
带键盘 - javascript - 使用 vanilla JS 在循环的每次迭代中设置延迟
- java - 使用@MethodSource 处理异常
- javascript - 流星插入函数中的 this.userId 未返回
- excel - 通过浏览数据选择文件夹中的多个 Excel 文件
- r - 查找自第一个案例以来的天数
- sql - 在 SQL 中添加新列,字符串来自现有列