You need to enable JavaScript to run this app. Flutter打开Drawer触发setState called during build错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Flutter打开Drawer触发setState called during build错误求助

Flutter 侧边栏触发_debugLocked报错修复方案

报错原因

你代码的问题出在ListTile的onTap属性赋值逻辑:你在buildListTile方法中直接执行了tapHandler()函数,而非将函数本身作为点击回调传递给onTap。
这会导致Widget处于构建阶段时,就直接执行了tapHandler内部的路由跳转逻辑,而Flutter禁止在视图构建过程中执行导航、状态更新这类修改视图树的操作,因此触发了!_debugLocked断言失败的报错。

修复方法

只需要修改buildListTile方法中onTap的赋值逻辑即可:

错误代码

onTap: tapHandler()

正确代码

onTap: tapHandler

修改后完整的MainDrawer代码如下:

import 'package:flutter/material.dart';
import 'package:recipes/screens/filters_screen.dart';

class MainDrawer extends StatelessWidget {
  const MainDrawer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Widget buildListTile(String title, IconData icon, Function tapHandler) {
      return ListTile(
          leading: Icon(
            icon,
            size: 26,
          ),
          title: Text(
            title,
            style: TextStyle(
                fontFamily: 'RobotoCondensed',
                fontSize: 24,
                fontWeight: FontWeight.bold),
          ),
          // 这里改为直接传递函数引用,不立刻执行
          onTap: tapHandler);
    }

    return Drawer(
        child: Column(
      children: [
        Container(
          height: 120,
          width: double.infinity,
          padding: EdgeInsets.all(20),
          alignment: Alignment.centerLeft,
          color: Theme.of(context).accentColor,
          child: Text(
            'Cooking up!',
            style: TextStyle(
                fontWeight: FontWeight.w900,
                fontSize: 30,
                color: Theme.of(context).primaryColor),
          ),
        ),
        SizedBox(
          height: 20,
        ),
        buildListTile('Meals', Icons.restaurant, () {
          Navigator.of(context).pushNamed('/');
        }),
        buildListTile('Filters', Icons.settings, () {
          Navigator.of(context).pushNamed(FilterScreen.routeName);
        }),
      ],
    ));
  }
}

原理说明

加括号的tapHandler()代表立刻执行该函数,拿到函数返回值赋值给onTap;不加括号的tapHandler代表将函数本身作为参数传递,只有当用户真正点击ListTile时,Flutter才会调用这个函数执行内部的跳转逻辑,不会在构建阶段触发违规操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 19:00:01