前言
知难行易,还是知易行难?笔者以为,答案应该从目标去寻找。目标是学习Flutter,知是一门语言,一个框架只是功夫深铁杆总能磨成针;行是每天下班回来打开电脑。对于这点,笔者以为知易行难。手总是无法抑制的选择了TIMI和TIKTOK。目标是快速掌握Flutter,知是Flutter的路径和方法;行依然是每天下班回来打开电脑。兜兜转转一个多月,依然是蜻蜓点水。知难知难,何时醍醐灌顶?
笔者偶得《Flutter实战.pdf》,便依法修炼。
路由
路由(Route)在移动开发中通常指⻚⾯(Page),这跟web开发中单⻚应⽤的Route概念意义是相同的,Route在 Android中通常指⼀个Activity,在iOS中指⼀个ViewController。所谓路由管理,就是管理⻚⾯之间如何跳转,通常也可 被称为导航管理。这和原⽣开发类似,⽆论是Android还是iOS,导航管理都会维护⼀个路由栈,路由⼊栈(push)操作对 应打开⼀个新⻚⾯,路由出栈(pop)操作对应⻚⾯关闭操作,⽽路由管理主要是指如何来管理路由栈。
实例一:
在Flutter自动生成的计数器基础上。
- 创建⼀个新路由,命名“NewRoute”
class NewRoute extends StatelessWidget {
const NewRoute({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("New route"),
),
body: const Center(
child: Text("This is new route"),
),
);
}
}
- 在 _MyHomePageState.build ⽅法中的 Column 的⼦widget中添加⼀个按钮
Widget build(BuildContext context) {
// 此处滤去无关代码
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// 此处滤去无关代码
FloatingActionButton(
child: const Icon(Icons.add_road_rounded),
tooltip: "open new route",
heroTag: 'other',
onPressed: () {
Navigator.pushNamed(context, "new_page");
Navigator.push(context,
MaterialPageRoute(builder: (context) {
return const NewRoute();
}));
},
),
],
// 此处滤去无关代码
运行效果
将鼠标放到中间按键,会出现提示。然后点击就会进入新页面。
实例二:
命名路由
- 在实例一的基础上修改MyApp.build方法,注册路由
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
routes: {
"new_page": (context) => const NewRoute(),
},
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
- 修改按键回调
Navigator.pushNamed(context, "new_page");
// Navigator.push(context,
// MaterialPageRoute(builder: (context) {
// return const NewRoute();
// }));
运行效果跟实例是一样的。不再展示。
题外
文中较多引用了《Flutter实战.pdf》,作者若寻来,要求笔者删改,笔者自当遵循。原文中,作者使用的SDK应该比较旧。笔者也做了相应的修改。