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......");
  }
}
相关推荐
朝朝辞暮i2 小时前
C++ 第 23 课:class —— 开始真正进入面向对象
开发语言·c++·算法
小师兄吃牛肉3 小时前
C语言篇:宏
c语言·开发语言
郑同学的笔记4 小时前
【c++随笔28】strcmp 和 memcmp对比
开发语言·c++
言乐64 小时前
Python根据无法识别搜索词找出可能输入内容模型
开发语言·python·django·virtualenv·pygame
weixin_307779134 小时前
有限产能智能排产与动态重排智能体:从需求解构到技术实现
开发语言·人工智能·算法·架构
kakakahahahaha4 小时前
Windows C盘临时文件清理:%temp%、Windows Temp、Prefetch、Windows.old与hiberfil.sys处理指南
c语言·开发语言·windows
朝朝辞暮i5 小时前
C++ 第 27 课:智能指针 shared_ptr
开发语言·c++·算法
朝朝辞暮i5 小时前
C++ 第 29 课:回调函数 Callback
开发语言·c++·算法
笨笨饿5 小时前
140_AI新手村MCP与Skills是干嘛的
开发语言·人工智能·python·stm32·单片机·嵌入式硬件·物联网
YOLO数据集集合6 小时前
EvoAgent:面向PR研发治理的自进化Multi-Agent Harness系统
java·开发语言·目标检测·agent·自进化