flutter Navigator跳转报错

Navigator operation requested with a context that does not include a Navigator.

The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.

这个报错是:因为你尝试使用 Navigator 操作(如 push 或 pop)的 BuildContext 并不在任何 Navigator 的子树中。这意味着你可能在一个没有正确 BuildContext 的地方执行了导航操作。

解决:在MyApp(你的首页)外层再套一个MaterialApp这样就能启用Navigator导航了。

另:如果你要使用Navigator.pushNamed(context, '/image_local_path'); 路由可以注册在这个最顶层的MaterialApp中,代码如下:

Dart 复制代码
void main() {
  // runApp(const MyApp());
  //TODO 要外包一个MaterialApp在起始页面,才可以使用Navigator来跳转
  runApp(
      //TODO 如果要加路由在这里,就不能用const来修饰
      // const MaterialApp(
      MaterialApp(
    routes: {
      '/image_local_path': (context) => const ImageLocalPathApp(),
      '/image_network': (context) => const ImageNetworkApp(),
      '/input_app_text_filed': (context) => const InputTextFiledApp(),
      '/input_app_form': (context) => const InputFormApp(),
    },
    title: "起始页面",
    home: const MyApp(),
  ));
}


class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late bool isShowChild;

  //当widget第一次插入到widget树时会被调用,
  //对于每次各state对象,flutter framework 只会调用一次
  @override
  void initState() {
    super.initState();
    isShowChild = true;
    debugPrint("parent initState......");
  }

  //初始化时,在initState()之后立刻调用
  //当一栏的InheritedWidget rebuild,会出发此方法被调用
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    debugPrint("parent didChangeDependencies......");
  }

  //绘制界面,当setState触发的时候会再次被调用
  @override
  Widget build(BuildContext context) {
    debugPrint("parent build ......");
    return MaterialApp(
      //主页面 Scaffold:Material Design布局结构的基础实现
      home: Scaffold(
        appBar: AppBar(title: const Text("Text")),
        //ScrollView是一个抽象类,所以不能直接用
        // body: ScrollView(
        body: SingleChildScrollView(
          physics: const BouncingScrollPhysics(),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    isShowChild = !isShowChild;
                  });
                },
                child: isShowChild ? const Child() : const Text("演示清除Child"),
              ),
              const SizedBox(height: 16), // 添加一些间距
              _textBody(),
              const Icon(Icons.star, size: 60, color: Colors.amber),
              const SizedBox(height: 16), // 添加一些间距
              const Text('Welcome!', style: TextStyle(fontSize: 24)),
              const SizedBox(height: 16), // 添加一些间距
              _richTextBody(),
              _defaultStyle(),
              flutterLogo(),
              icon(),
              Image.asset("assets/payment_black.png"),
              Image.network("https://www.baidu.com/img/bdlogo.png"),
              const CircleAvatar(
                //图片提供者 ImageProvider
                backgroundImage: AssetImage("assets/head.jpg"),
                //半径,控制大小
                radius: 50.0,
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.pushNamed(context, '/image_local_path');

                  // Navigator.push(
                  //   context,
                  //   MaterialPageRoute(
                  //       builder: (context) => const ImageLocalPathApp()),
                  // );
                },
                child: const Text('Go to Second Page'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  //状态改变的时候会调用该方法,比如调用了setState
  @override
  void didUpdateWidget(covariant MyApp oldWidget) {
    super.didUpdateWidget(oldWidget);
    debugPrint("parent didUpdateWidget......");
  }

  //当state对象从树中被移除时,会调用此回调
  @override
  void deactivate() {
    super.deactivate();
    debugPrint("parent deactivate......");
  }

  //当state对象从树中永久移除的时候调用;
  //通常在此回调中释放资源
  @override
  void dispose() {
    super.dispose();
    debugPrint("parent dispose......");
  }
}
相关推荐
xxie1237941 小时前
return与print
开发语言·python
秋91 小时前
从 Python 后端工程师转型 AI Engineer(AI 工程化)的完整补课清单(2026实战版)
开发语言·人工智能·python
程序员二叉2 小时前
【Java】 异常高频面试题精讲 | 易错点+对比总结
java·开发语言·面试
慕木沐2 小时前
Google ADK Java 1.0版本 核心机制与实战 Demo
java·开发语言·python
Roann_seo%2 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++
huangdong_3 小时前
淘宝商品SKU图自动分类技术深度解析:从DOM解析到智能归档
开发语言·javascript·ecmascript
阿正的梦工坊3 小时前
【Rust】12-借用检查器与非词法生命周期
开发语言·后端·rust
qq_2518364574 小时前
基于java Web网络订餐系统设计与实现 源码文档
java·开发语言·前端
秋94 小时前
3年经验Python后端转AI Engineer:3个月实战转型计划(2026版)
开发语言·人工智能·python
凡人叶枫4 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法