我正在尝试在onTap中启动一个新屏幕,但是我收到以下错误:
Navigator operation requested with a context that does not include a
Navigator.
我用来导航的代码是:
onTap: () { Navigator.of(context).pushNamed('/settings'); },
我在我的应用程序中设置了一条路线,如下所示:
routes: <String,WidgetBuilder>{ '/settings': (BuildContext context) => new SettingsPage(),},
我试图使用stocks示例应用程序复制代码.我查看了Navigator和Route文档,但无法弄清楚如何使用Navigator包含上下文. onTap中使用的上下文是从传递给构建方法的参数中引用的:
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) {
SettingsPage是一个类,如下所示:
class SettingsPage extends Navigator { Widget buildAppBar(BuildContext context) { return new AppBar( title: const Text('Settings') ); } @override Widget build(BuildContext context) { return new Scaffold( appBar: buildAppBar(context),); } }
解决方法
我在flutter应用程序中设置了这个简单的路由示例:
import 'package:flutter/material.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo',home: new MyHomePage(),routes: <String,WidgetBuilder>{ '/settings': (BuildContext context) => new SettingsPage(),); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('TestProject'),),body: new Center( child: new FlatButton( child: const Text('Go to Settings'),onPressed: () => Navigator.of(context).pushNamed('/settings') ) ) ); } } class SettingsPage extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('SettingsPage'),body: new Center( child: new Text('Settings') ) ); } }
请注意,SettingsPage扩展了StatelessWidget而不是Navigator.我无法重现您的错误.
此示例是否可以帮助您构建应用程序?如果我可以帮助你,请告诉我.