Flutter 入门与实战:路由参数处理
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
initialRoute: '/',
routes: {
'/': (context) => FirstScreen,
'/second': (context) => SecondScreen,
},
);
}
}
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: RaisedButton(
child: Text('Go to second screen'),
onPressed: () {
Navigator.pushNamed(context, '/second');
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
static const routeName = '/second';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Screen'),
),
body: Center(
child: Text(
'This is the second screen',
style: TextStyle(fontSize: 24),
),
),
);
}
}
这个代码示例展示了如何在Flutter中定义和使用带有静态路由名称的路由参数。在MyApp
类中,我们定义了两个路由,一个是初始路由/
,另一个是/second
。在FirstScreen
中,我们使用Navigator.pushNamed
方法导航到/second
路由。在SecondScreen
中,我们定义了一个静态的路由名称常量routeName
,这样可以在其他地方(如在MyApp
类中定义路由表时)引用此路由名称。
评论已关闭