草庐IT

android - 如何修复 flutter 异常 : Navigator operation requested with a context that does not include a Navigator

coder 2023-07-22 原文

我正在尝试使用 flutter 框架创建抽屉导航, 但是我每次运行它都会遇到以下异常

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

那么解决方案是什么,有什么帮助吗?

我使用 Navigator 类如下

void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new AppStates();
  }
}

class AppStates extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return MaterialApp(
      home: new Scaffold(
        appBar: AppBar(
          title: Text("Application App Bar"),
        ),
        drawer: Drawer(
          child: ListView(
            children: <Widget>[
              ListTile(
                title: Text("Next Page"),
                onTap: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => NextPage()));
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

NextPage类的代码是

class NextPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Next Page App Bar"),
        ),
      ),
    );
  }
}

最佳答案

您似乎没有为当前上下文设置导航器。您应该尝试将 MaterialApp 作为您的根应用程序,而不是使用 StatefulWidget。 MaterialApp 为您管理一个导航器。这是一个如何在 main.dart 中设置应用程序的示例

void main() {
 runApp(MaterialApp(
   title: 'Navigation Basics',
   home: MyApp(),
 ));
}

关于android - 如何修复 flutter 异常 : Navigator operation requested with a context that does not include a Navigator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600412/

有关android - 如何修复 flutter 异常 : Navigator operation requested with a context that does not include a Navigator的更多相关文章

随机推荐