首页 > 解决方案 > Navigation.of(context) 不去另一条路线

问题描述

我正在尝试使用以下代码前往新路线,但它不起作用。我的 IDE 中没有显示任何错误,而且我的代码似乎与我检查过的有关如何转到新页面的所有资源非常相似。

我已经将我的代码与其他在线代码进行了比较。我猜它是如何实现的。我也尝试过使用:

    MaterialPageRoute(builder: (context) => SecondRoute())

但这不是问题所在。这是我的大部分应用程序:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    Widget setTimer = Container(
      decoration: BoxDecoration(
          border: Border.all(color: Colors.purpleAccent,width: 3)
      ),
      padding: EdgeInsets.all(32),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          RaisedButton(
            child: Text('Set Timer'),
            onPressed: (){
              //Go to the second route
              Navigator.of(context).pushNamed('/page2');
            },
          )
        ],
      ),
    );
    return MaterialApp(
      title: 'Hands Off',
      routes: <String, WidgetBuilder>{
        '/page2': (BuildContext context) => SecondRoute(),
      },
      home: Scaffold(
        appBar: AppBar(
          title: Text('Timer config'),
        ),
        body: Column(
          children: <Widget>[

            setTimer,
          ],
        ),
      ),
    );
  }
}
class SecondRoute extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    Widget firstRouteButton = Container(
      child: Row(
        children: <Widget>[
          RaisedButton(
            child: Text('Go back'),
            onPressed: (){
              //Go back to main route (first route)
              Navigator.of(context).pop(true);
            },
          )
        ],
      ),
    );
    return Scaffold(
      appBar: AppBar(
        title: Text('hel'),
      ),
    );
  }
}

它应该转到一个新页面,但是每当我按下按钮时,什么都没有发生。你们能解释一下为什么它不能正常工作吗?

标签: flutter

解决方案


很简单。

使用 aBuilder向下传递上下文。

Builder(builder: (BuildContext context) {
          return Whatever_Widget;
        },)

所以代码将是

        body: Builder(builder: (BuildContext context) {
          return Column(
            children: <Widget>[
              Container(
                decoration: BoxDecoration(border: Border.all(color: Colors.purpleAccent, width: 3)),
                padding: EdgeInsets.all(32),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    RaisedButton(
                      child: Text('Set Timer'),
                      onPressed: () {
                        //Go to the second route
//                        Navigator.of(context).push(MaterialPageRoute(builder: (context) => SecondRoute()));
                        Navigator.of(context).pushNamed('/page2');
                      },
                    )
                  ],
                ),
              ),
            ],
          );
        },)

推荐阅读