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......");
  }
}
相关推荐
岭南灯火8 分钟前
前端通用交互式几何编辑器的设计法则 3 - 数据对象的设计
前端·javascript·架构
岭南灯火15 分钟前
前端通用交互式几何编辑器的设计法则 2 - 交互事件流
前端·javascript·架构
岭南灯火23 分钟前
前端通用交互式几何编辑器的设计法则 1 - 入口的对象及其成员
前端·javascript·架构
满栀5851 小时前
Vue.js 接口封装最佳实践:从基础到高级
前端·javascript·vue.js
牛艺翔1 小时前
C++基础
开发语言·c++
键盘会跳舞1 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
kyriewen2 小时前
我踩了三次同一个坑才明白:React里"改了数据却不重新渲染"的真正原因
前端·javascript·react.js
美味蛋炒饭.2 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
我星期八休息2 小时前
网络编程—网络层
开发语言·前端·网络·人工智能·智能路由器
不负岁月无痕2 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试