Flutter路由使用
Flutter的路由使用有两种方式,分别是新建路由和注册路由。新建路由代码如下:import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget{@overrideWidget build(BuildContext context){return
·
Flutter的路由使用有两种方式,分别是新建路由和注册路由。
新建路由
- 代码如下:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return MaterialApp(
title: "Welcome to Flutter",
home: FirstPage(),
);
}
}
/// 第一个页面
class FirstPage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("第一页"),
),
body: Padding(
padding: EdgeInsets.all(30.0),
child: RaisedButton(
child: Text('跳转到第二页'),
onPressed: (){
Navigator.push(//在路由栈添加路由
context,
MaterialPageRoute(builder: (context) => SecondPage())
);
},
),
),
);
}
}
///第二个页面
class SecondPage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("第二页"),
),
body: Padding(
padding: EdgeInsets.all(30.0),
child: RaisedButton(
child: Text("回到第一页"),
onPressed: (){//在路由栈移除路由
Navigator.pop(context);
},
),
),
);
}
}
注册路由
它以堆叠的方式,叠加页面。因此,在返回第一个页面的时候,需要从栈中销毁第二个页面,否则,会再次堆叠一个新的页面,就像Web前端的页面一样。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return MaterialApp(
title: "Welcome to Flutter",
home: FirstPage(),
routes: <String, WidgetBuilder>{
'/first':(BuildContext context) => FirstPage(),
'/second':(BuildContext context) => SecondPage(),
},
initialRoute: 'first',
);
}
}
/// 第一个页面
class FirstPage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("第一页"),
),
body: Padding(
padding: EdgeInsets.all(30.0),
child: RaisedButton(
child: Text('跳转到第二页'),
onPressed: (){
Navigator.pushNamed(context, '/second');
},
),
),
);
}
}
///第二个页面
class SecondPage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("第二页"),
),
body: Padding(
padding: EdgeInsets.all(30.0),
child: RaisedButton(
child: Text("回到第一页"),
onPressed: (){
Navigator.of(context).pop();
},
),
),
);
}
}
更多推荐



所有评论(0)