flutter - 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'),
),
);
}
}
它应该转到一个新页面,但是每当我按下按钮时,什么都没有发生。你们能解释一下为什么它不能正常工作吗?
解决方案
很简单。
使用 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');
},
)
],
),
),
],
);
},)
推荐阅读
- reactjs - 将按钮映射到材质 ui-table 的行
- python - 匹配和加入列表中字典的键/值
- gis - 来自 tmap 对象的 SHP
- javascript - Typescript/JS 递归承诺
- git - 如何在 Github 中保留文件的内容类型?
- java - 有没有办法在java中将输入从案例1到案例2?
- python-3.x - 导入 Seaborn 的问题
- javascript - 如何在javascript中根据条件显示数字列表
- c# - 将查询字符串从 VBA 转换为 C# 并使用 HttpClient 发送
- firebase - 在 React Native 中不显示 console.log(action)