dart - flutter 导航器不工作

我有两个屏幕的应用程序,我想通过按下按钮从第一个屏幕推送到第二个屏幕。

屏幕 1

import 'package:flutter/material.dart';
import './view/second_page.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new MainScreen();
  }
}

class MainScreen extends State<MyApp> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        home: new Scaffold(
            appBar: new AppBar(
                title: new Text("Title")
            ),
            body: new Center(
                child: new FlatButton(child: new Text("Second page"),
                    onPressed: () {
                      Navigator.push(context,
                          new MaterialPageRoute(
                              builder: (context) => new SecondPage()))
                    }
                )
            )
        )
    );
  }
}

屏幕 2

import 'package:flutter/material.dart';

class SecondPage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return new SecondPageState();
  }
}


class SecondPageState extends State<SecondPage> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Title"),
      ),
      body: new Center(
        child: new Text("Some text"),
      ),
    );
  }
}

推送没有发生,我得到了这个

The following assertion was thrown while handling a gesture: 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.

Another exception was thrown: Navigator operation requested with a context that does not include a Navigator.

怎么了?

最佳答案

将 Flutter 中的小部件想象成一棵树,其上下文指向使用 build 函数构建的任何节点。在你的情况下,你有

MainScreen    <------ context
  --> MaterialApp
   (--> Navigator built within MaterialApp)
      --> Scaffold
        --> App Bar
          --> ...
        --> Center
          --> FlatButton

因此,当您使用上下文查找导航器时,您使用的是不在导航器下方的 MainScreen 上下文。

您可以创建一个新的 Stateless 或 Stateful Widget 子类来包含您的 Center + FlatButton,因为其中的构建函数将指向该级别,或者您可以使用 Builder并定义 builder 回调(它有一个指向 Builder 的上下文)以返回 Center + FlatButton。

关于dart - flutter 导航器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50124355/

相关文章:

android-studio - 无法将 Flutter 项目迁移到 AndroidX

flutter - 在 float 操作按钮上的 onPressed 回调中从脚手架显示 snack

firebase - Flutter 中从 Firestore 查询单个文档(cloud_fires

ios - 使用 Swift 创建 Flutter 项目

dart - 错误 : The name 'Image' is defined in the lib

dart - Flutter Firestore 服务器端时间戳

flutter - 如何在不同的屏幕尺寸上测试 Flutter 小部件?

dart - Flutter BottomNavigationBar 不能处理三个以上的项目

android - 在 flutter 中打开对话框时检测返回按钮按下

android - flutter 意外退出