You need to enable JavaScript to run this app. Flutter中DropdownButton选中值不更新、始终显示Tone 1如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中DropdownButton选中值不更新、始终显示Tone 1如何解决

问题原因

你将状态变量_value定义在了build方法内部,每次调用setState触发页面重绘时,build方法都会重新执行,_value会被强制重置为初始值1,所以DropdownButton的选中状态始终停留在Tone 1。同时你将横屏配置写在了build方法中,也会导致每次页面重绘都重复执行不必要的配置逻辑。

修复方案
  1. 将int _value=1;从build方法中移出去,作为当前State类的成员变量
  2. 将SystemChrome.setPreferredOrientations的调用移到initState生命周期中,保证全局只执行一次配置

修改后的核心代码示例:

class TonesPageState extends State<TonesPage> {
  // 状态变量作为类成员,不会随build执行被重置
  int _value = 1;

  @override
  void initState() {
    super.initState();
    // 横屏配置移到initState,全局仅执行一次
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
  }

  @override
  Widget build(BuildContext context) {
    // 删掉原来在此处的_value定义和setPreferredOrientations调用
    return MaterialApp(
      // 其余原有代码保持不变即可
      home: Scaffold(
        appBar: AppBar(
          title: Text('Tones'),
          backgroundColor: Colors.black,
          actions: <Widget>[
            DropdownButton<int>(
              value: _value,
              dropdownColor:Colors.black26,
              items: [
                DropdownMenuItem(
                  child: Text("Tone 1",
                    style: TextStyle(
                      color: Colors.white ,
                      fontSize: 20,
                      letterSpacing: 0.5,
                    ),
                  ),
                  value: 1,
                ),
                // 其余DropdownMenuItem保持不变
              ],
              onChanged: (value) {
                setState(() {
                  _value = value!;
                });
              }
            ),
            // 其余原有组件逻辑保持不变
          ],
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者Sam12

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 16:36:08