Flutter自定义AppBar添加路由导航时出现Undefined name 'context'错误
解决自定义AppBar的"Undefined name 'context'"错误
问题原因:你写的
customAppBarTest函数没有传入BuildContext参数,而Navigator的路由操作必须依赖上下文才能执行。默认AppBar是在Widget树内部使用,天然持有上下文,所以不会出现这个错误。修复方案:
- 给
customAppBarTest函数添加BuildContext context参数 - 在调用该组件时传入当前页面的上下文
- 给
修复后的函数代码:
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
相关产品推荐
相关产品推荐

