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......");
  }
}
相关推荐
AI原吾几秒前
探索SVG的奥秘:Python中的svgwrite库
android·开发语言·python·svgwrite
Tinalee-电商API接口呀10 分钟前
python爬虫爬取淘宝商品比价||淘宝商品详情API接口
大数据·开发语言·人工智能·爬虫·python·json
前端小程11 分钟前
使用vant UI实现时间段选择
前端·javascript·vue.js·ui
week_泽11 分钟前
安装python,jupter notebook,anaconda换源
开发语言·python
星空下夜猫子25 分钟前
JAVA 使用POI实现单元格行合并生成
java·开发语言
whyfail33 分钟前
React 事件系统解析
前端·javascript·react.js
禾苗种树35 分钟前
element form rules 验证数组对象属性时如何写判断规则
javascript·vue.js·elementui
liangshanbo121536 分钟前
JavaScript 中的一些常见陷阱
开发语言·javascript·ecmascript
VaporGas1 小时前
掌握Java封装:以猜拳小游戏为例,深入理解OOP
java·开发语言·学习·面向对象编程·oop·猜拳游戏·封装思想
Bitup_bitwin1 小时前
C++中的for-each循环
开发语言·c++