You need to enable JavaScript to run this app. Flutter调用Navigator.push跳转页面时抛出“上下文未包含Navigator”异常
优惠活动
大模型
产品
解决方案
定价
更多

Flutter调用Navigator.push跳转页面时抛出“上下文未包含Navigator”异常

报错核心原因
  • 调用Navigator.push时传入的context是MyApp组件build方法的顶层context,这个context位于MaterialApp组件的外层子树范围。Navigator路由组件是MaterialApp内部自动构建的子组件,只有处于Navigator子树内部的context才能正常定位到实例、执行跳转操作,传入外层context就会触发“上下文未包含Navigator”的断言。
  • 原代码存在组件结构错误:MaterialApp的根页面需要通过home命名参数传入,代码直接把SafeArea作为位置参数传给MaterialApp构造函数,本身不符合组件的使用规范,会导致内部组件树构建异常。
修正操作步骤
  • 调整MaterialApp的入参,将根页面内容绑定到home命名参数下,保证内部的Navigator组件正常挂载
  • 替换跳转逻辑使用的context,不要直接用MyApp的顶层context,可通过两种方式获取合法context:
    • 用Builder组件包裹需要触发跳转的按钮区域,Builder回调会提供一个处于Navigator子树范围内的context,直接用这个context发起跳转即可
    • 将根页面抽成独立的页面组件,在组件自身的build方法中获取的context天然位于Navigator子树内,可直接用于路由操作
可运行的参考修正代码
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          backgroundColor: Colors.red[100],
          body: Column(
            children: [
              const SizedBox(height: 50),
              Align(
                alignment: Alignment.center,
                child: Image.asset(
                  "assets/icons/appicon.png",
                  height: 150,
                ),
              ),
              Align(
                alignment: Alignment.bottomCenter,
                child: Builder(
                  builder: (innerContext) => ElevatedButton(
                    child: const Text('Click Picture'),
                    style: ElevatedButton.styleFrom(backgroundColor: Colors.red[800]),
                    onPressed: () {
                      Navigator.push(
                        innerContext,
                        MaterialPageRoute(builder: (context) => const CameraRoute()),
                      );
                    },
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

说明:原代码使用的RaisedButton已在Flutter新版本中标记为废弃,参考代码中替换为官方推荐的ElevatedButton实现同等按钮样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.08 16:36:09