Flutter.io Navigator errors in appbar

时间:2018-03-25 20:23:57

标签: dart flutter

I've decided to give flutter a try and stumbled upon the following problem:

In my app I would like to have a button in the AppBar that would take the user to another screen. However whenever I attempt to call Navigator in any of the IconButtons' onPressed handlers, I get the following error:

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.

Here's my main.dart (minus the imports):

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var service = new ProjectService();

    return new MaterialApp(
        theme: new ThemeData(
          primaryColor: Colors.deepOrange,
        ),
        home: new Scaffold(
          appBar: new AppBar(
              title: new Text("My App Title"),
              actions: 
              <Widget>[
                new IconButton(
                    icon: new Icon(Icons.add),
                    onPressed: () =>
                        Navigator.of(context).pushNamed("/projects/add")) //<-- Here's where I get the exception
              ],
              elevation: 0.0),
          body: new Center(child: new ProjectList(projects: service.toList())), //<-- Exactly the same code runs fine here
          drawer: new AppDrawer(),
        ),
        routes: <String, WidgetBuilder>{
          '/projects/add': (BuildContext context) => new ProjectAddScreen(),
          '/projects/test': (BuildContext context) => new ProjectAddScreen(),
          '/settings': (BuildContext context) => new AppSettingsScreen(),
          '/about': (BuildContext context) => new AboutScreen()
        });
  }
}

This is the only place where the app instance is constructed and AppBar is the standard AppBar that comes bundled with the flutter/material package.

My flutter doctor output if that's of any relevance

[√] Flutter (Channel master, v0.2.5-pre.41, on Microsoft Windows [Version 10.0.16299.309], locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK 26.0.2)
    X Android license status unknown. // I use the SDK manager from Visual Studio
[!] Android Studio (version 3.0)
    X Unable to determine bundled Java version. //I use the SDK manager from Visual Studio so I have no need in Android Studio
[√] VS Code, 64-bit edition (version 1.21.1)
[√] Connected devices (1 available)

1 个答案:

答案 0 :(得分:0)

虽然Rémi在对这个问题的评论中指出(抱歉,我不知道如何正确提及他的用户),但结果却是this thread的副本。但是因为我发现代码中提供的代码有点脱离了上下文,我认为值得一提的是我如何应用我在特定用例中提供的解决方案。

我做了一些调试,发现当我在onPressed的{​​{1}}处理程序中时,上下文不是IconButton或{{1} }。这是IconButton的。如果你问我这个问题既合乎逻辑又奇怪,特别是考虑到将相同的代码放在正文中心的工作。

但是,尽管如此,我打开了Stocks示例应用程序,看看他们如何构建应用程序并简单地遵循他们在那里使用的模式。

这是我最终的结果:

<强> main.dart

AppBar

<强> HomeScreen.dart

MaterialApp