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

Flutter中setState应如何调用?自定义导航栏切换无响应问题排查

你的代码存在两个核心错误:

  • 第一:状态变量的存放位置错误
    你将控制页面索引的_current变量和色块列表pages都定义在了build方法内部,而Flutter每次触发组件重绘都会全量执行build方法,这就意味着不管你在点击回调中把_current改成什么值,只要组件重绘,_current就会被重置为初始值1。这两个变量应该作为_CustomNavState类的成员变量,放在build方法外部。
  • 第二:setState调用缺失的逻辑错误
    你的认知完全错误:_current变更后会直接影响你展示的色块是pages数组中的哪一个,这本身就是明确的界面内容变更,必须调用setState方法通知Flutter框架重新执行build方法渲染最新的界面,否则修改的_current只是内存中的临时变量,不会触发界面更新。

修正后的完整代码如下:

import 'package:flutter/material.dart';

class CustomNav extends StatefulWidget {
  const CustomNav({Key? key}) : super(key: key);

  @override
  _CustomNavState createState() => _CustomNavState();
}

class _CustomNavState extends State<CustomNav> {
  // 状态变量作为State类的成员变量存放
  int _current = 1;
  final List<Widget> pages = [
    Container(
      color: Colors.white,
      width: 50,
      height: 50,
    ),
    Container(
      color: Colors.yellow,
      width: 50,
      height: 50,
    ),
    Container(
      color: Colors.green,
      width: 50,
      height: 50,
    )
  ];

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Container(
      color: Colors.blue,
      width: width,
      height: 100,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          pages[_current],
          IconButton(
              onPressed: () {
                // 状态变更后调用setState触发重绘
                setState(() {
                  _current = 0;
                });
                print(_current);
              },
              icon: Icon(Icons.ac_unit)),
          IconButton(
              onPressed: () {
                setState(() {
                  _current = 1;
                });
                print(_current);
              },
              icon: Icon(Icons.ac_unit)),
          IconButton(
              onPressed: () {
                setState(() {
                  _current = 2;
                });
                print(_current);
              },
              icon: Icon(Icons.ac_unit))
        ],
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:57:01