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

Flutter自定义AppBar添加路由导航时出现Undefined name 'context'错误

解决自定义AppBar的"Undefined name 'context'"错误
  • 问题原因:你写的customAppBarTest函数没有传入BuildContext参数,而Navigator的路由操作必须依赖上下文才能执行。默认AppBar是在Widget树内部使用,天然持有上下文,所以不会出现这个错误。

  • 修复方案:

    1. 给customAppBarTest函数添加BuildContext context参数
    2. 在调用该组件时传入当前页面的上下文

修复后的函数代码:

Widget customAppBarTest(BuildContext context, String title, bool backButton, bool home, bool about) {
  return AppBar(
    centerTitle: true,
    title: Center(
      child: Text(title),
    ),
    automaticallyImplyLeading: false,
    leading: backButton ? GestureDetector(
        onTap: () {
          print('Go previous screen');
          Navigator.pop(context);
        },
        child: const Icon(Icons.arrow_back)) : null,
    actions: [
      if(home) GestureDetector(
          onTap: () {
            print('Go home');
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const HomeMenu(),
              ),
            );
          },
          child: const Icon(Icons.home))
    ],
  );
}

调用示例:

Scaffold(
  appBar: customAppBarTest(context, "测试页面", true, true, false),
  body: // 页面内容
)

更推荐的写法是改成组件类(符合Flutter规范):

class CustomAppBarTest extends StatelessWidget {
  final String title;
  final bool backButton;
  final bool home;
  final bool about;

  const CustomAppBarTest({
    super.key,
    required this.title,
    required this.backButton,
    required this.home,
    required this.about,
  });

  @override
  Widget build(BuildContext context) {
    return AppBar(
      centerTitle: true,
      title: Center(child: Text(title)),
      automaticallyImplyLeading: false,
      leading: backButton ? GestureDetector(
        onTap: () => Navigator.pop(context),
        child: const Icon(Icons.arrow_back),
      ) : null,
      actions: [
        if(home) GestureDetector(
          onTap: () => Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const HomeMenu()),
          ),
          child: const Icon(Icons.home),
        )
      ],
    );
  }
}

类组件调用示例:

Scaffold(
  appBar: const CustomAppBarTest(
    title: "测试页面",
    backButton: true,
    home: true,
    about: false,
  ),
  body: // 页面内容
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:42:45