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

Flutter路由跳转报Navigator operation requested with a context that does not include a Navigator错误解决

错误根因

你当前调用Navigator使用的context来自SignIn组件的build方法,这个context的层级在你返回的MaterialApp之上,而Navigator是MaterialApp内部才会初始化的组件,上层的context无法找到可用的Navigator实例,就会抛出这个报错。

修复方案

  • 方案1:将MaterialApp移到更上层的根组件中,SignIn组件仅负责返回Scaffold及内部页面内容,这样SignIn拿到的context就处于MaterialApp的下层,能正常获取到Navigator。
    修改后代码参考:
// 项目根组件
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(  
      debugShowCheckedModeBanner: false,
      theme: ThemeData(fontFamily: 'Raleway'),
      home: const SignIn(),
    );
  }
}

// 调整后的SignIn组件
class SignIn extends StatelessWidget {
  const SignIn({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(children: [
          Text('Sign In', style: TextStyle(         
            color: Colors.orange,
            fontSize: 60.0) ),
          SizedBox(height:20,),
          TextField(
            decoration: InputDecoration(    
              border: OutlineInputBorder(),
              hintText: 'Email',
            ),
          ),
          TextField(
            decoration: InputDecoration(    
              border: OutlineInputBorder(),
              hintText: 'Password',
            ),
          ),
          SizedBox(height: 20,),
          ElevatedButton(  
            child: const Text('Sign In'),  
            onPressed: null,  
          ),  
          SizedBox(height: 15,),
          Text('Forgot Password ?', style: TextStyle(fontSize: 15),)
        ],
        ),
        margin: EdgeInsets.only(top: 200),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.purple,
              ),
              child: Image(image: AssetImage('Images/smsa logo.png'))
            ),
            ListTile(
              title: Text('My Account'),
              leading: IconButton(onPressed: (){
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => MyAccount() )
                );
              }, icon: Icon(Icons.account_circle))
            ),
          ],
        ),
      ),
    );
  }
}
  • 方案2:如果不想调整组件层级,可以给Scaffold套一层Builder组件,使用Builder提供的新context来调用Navigator,新的context处于MaterialApp下层,也能正常获取到Navigator实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:15:00