Flutter提示之Navigator operation requested with a context that does not include a Navigator.

布满荆棘的人生 2021-09-24 16:06 294阅读 0赞

1 、问题

用Flutter写了页面跳转,提示错误如下

  1. Navigator operation requested with a context that does not include a Navigator.

2 、我的代码

  1. void main() {
  2. runApp(MyApp1());
  3. }
  4. class MyApp1 extends StatelessWidget {
  5. @override
  6. Widget build(BuildContext context) {
  7. return MaterialApp(
  8. title: 'open url',
  9. home: Scaffold(
  10. appBar: AppBar(
  11. title: Text('hello flutter'),
  12. ),
  13. body: Column(
  14. mainAxisAlignment: MainAxisAlignment.center,
  15. mainAxisSize: MainAxisSize.min,
  16. children: <Widget>[
  17. FlatButton(
  18. child: Text("go to new page"),
  19. textColor: Colors.blue,
  20. onPressed: () {
  21. Navigator.push(context, MaterialPageRoute(
  22. builder:(context) => NewPage()));
  23. },
  24. ),
  25. ],
  26. ),
  27. ),
  28. );
  29. }
  30. }
  31. class NewPage extends StatelessWidget {
  32. @override
  33. Widget build(BuildContext context) {
  34. return Scaffold(
  35. appBar: AppBar(
  36. title: Text("hello word"),
  37. ),
  38. body: Center(
  39. child: Text("this is new page"),
  40. ),
  41. );
  42. }
  43. }

3、原因

  1. Navigator operation requested with a context that does not include a Navigator.

说明这个context上下文不一致,我们看下Navigator的继承关系

  1. class Navigator extends StatefulWidget {
  2. }

但是我的代码是这样的

  1. class MyApp1 extends StatelessWidget {
  2. }

我们需要使用StatefulWidget的Context

4、解决办法

  1. void main() {
  2. runApp(MaterialApp(
  3. title: "Navigation basics",
  4. home: MyApp1(),
  5. ));
  6. }

用MaterialApp启动

  1. class MaterialApp extends StatefulWidget {
  2. ***
  3. }

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读