You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:18:02