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中,代码如下:

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 {
  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: [
              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......");
  }
}

你可能感兴趣的:(javascript,开发语言,ecmascript)