Flutter中SwitchListTile开关按钮点击后UI状态无变化问题
问题原因
- 你在StatefulWidget中直接修改了状态变量
notifications,但没有调用Flutter提供的setState()方法。Flutter的UI渲染依赖状态快照,只有通过setState()修改状态变量时,框架才会感知到状态变化,触发组件重新构建刷新UI。你直接修改变量只会改变内存中的数值,不会触发重绘,因此控制台能打印最新值但开关UI无变化。
解决方法
- 将状态修改逻辑包裹在
setState()的回调函数中即可,修正后的代码如下:
class _PageOne extends State<Page> { bool notifications = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), drawer: Drawer(), body: Container( child: Column( children: [ SwitchListTile( title: Text("Allow Notifications"), secondary: Icon(Icons.notifications_active), value: notifications, onChanged: (val) { setState(() { notifications = val; }); print(notifications); }) ], ), )); } }
内容的提问来源于stack exchange,提问作者Karim Refaay
相关产品推荐
相关产品推荐

