可能真的很简单,但是我试图在主页上创建另一个按钮以遵循另一条路线。
[目前只有一个按钮可以将您带到路径X(又名“第一屏幕/主页”),但我希望另一个按钮可以将您带到路径Y。请问有什么建议吗?
预先加油!(对不起,您仍无法掌握该术语)
void main() {
runApp(MaterialApp(
title: 'Named Routes Demo',
initialRoute: '/',
routes: {
'/': (context) => FirstScreen(),
'/second': (context) => SecondScreen(),
'/second/third': (context) => ThirdScreen(),
},
)
);
}
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
),
body: Center(
child: RaisedButton(
child: Text('Search'),
onPressed: () {
Navigator.pushNamed(context, '/second');
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Results Page'),
),
body: Center(
child: RaisedButton(
child: Text('Click this result'),
onPressed: () {
Navigator.pushNamed(context, '/second/third');
},
),
),
);
}
}
class ThirdScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Items Page"),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('This is the item!'),
),
),
);
}
}
代替使用路由,可以使用onGenerateRoute参数
void main() {
runApp(MaterialApp(
title: 'Named Routes Demo',
home: FirstScreen(),
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute(builder: (context) {
if(settings.name == '/second/third') return ThirdScreen();
if(settings.name == '/second') return SecondScreen();
else return FirstScreen();
})
},
},
)
);
}
您可以将此逻辑更改为需要使用settings.name的任何方式
要在首页上添加另一个按钮,对于此简单代码,您可以使用Column小部件,这是示例
Center(
child: Column(
children: [
RaisedButton(
child: Text('Button one text'),
onPressed: () => Navigator.pushNamed(context, '/second'),
),
RaisedButton(
child: Text('Button two text'),
onPressed: () => Navigator.pushNamed(context, '/second/third'),
),
],
),
),