Flutter 路由导航: 源码探索与实战
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter 导航',
home: HomePage(),
routes: <String, WidgetBuilder>{
'/route1': (BuildContext context) => FirstRoute(),
'/route2': (BuildContext context) => SecondRoute(),
},
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('主页'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('去往 route1'),
onPressed: () {
Navigator.pushNamed(context, '/route1');
},
),
RaisedButton(
child: Text('去往 route2'),
onPressed: () {
Navigator.pushNamed(context, '/route2');
},
),
],
),
),
);
}
}
class FirstRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("route1"),
),
body: Center(
child: RaisedButton(
child: Text('返回主页'),
onPressed: () {
Navigator.pop(context);
},
),
),
);
}
}
class SecondRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("route2"),
),
body: Center(
child: RaisedButton(
child: Text('返回主页'),
onPressed: () {
Navigator.pop(context);
},
),
),
);
}
}
这段代码定义了一个简单的Flutter应用,展示了如何使用命名路由(routes)进行导航。应用包含一个主页、两个路由页面,以及如何在它们之间进行跳转。这是学习Flutter路由导航的一个很好的起点。
评论已关闭