导航管理主要是指手机程序界面的跳转管理。导航管理也成路由管理。手机程序界面在Android中通常指一个Activity,在iOS中指一个ViewController。这和原生开发类似,无论是Android还是iOS,导航管理都会维护一个界面栈,手机界面入栈(push)操作对应打开一个新页面,手机界面出栈(pop)操作对应页面关闭操作,而导航管理主要是指如何来管理手机界面栈。
我们在上一节“计数器”示例的基础上,做如下修改:
在main.dart当中创建一个新class,命名“NewRoute”。
class NewRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("New route"),
),
body: Center(
child: Text("This is new route"),
),
);
}
}
新class继承自StatelessWidget
,界面很简单,在页面中间显示一句"This is new route"。
在_MyHomePageState.build
方法中的Column
的子widget中添加一个按钮(FlatButton
) :
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
... //省略无关代码
FlatButton(
child: Text("open new route"),
textColor: Colors.blue,
onPressed: () {
//导航到新路由
Navigator.push( context,
new MaterialPageRoute(builder: (context) {
return new NewRoute();
}));
},
),
],
)
我们添加了一个打开新页面的按钮,并将按钮文字颜色设置为蓝色,点击该按钮后就会打开新的路由页面。程序运行效果如下图所示。
4.代码分析
(1)MaterialPageRoute
MaterialPageRoute
继承自PageRoute
类,PageRoute
类是一个抽象类,表示占有整个屏幕空间的一个模态路由页面,它还定义了路由构建及切换时过渡动画的相关接口及属性。MaterialPageRoute
是Material组件库的一个Widget,它可以针对不同平台,实现与平台页面切换动画风格一致的路由切换动画:
下面我们介绍一下MaterialPageRoute
构造函数的各个参数的意义:
MaterialPageRoute({
WidgetBuilder builder,
RouteSettings settings,
bool maintainState = true,
bool fullscreenDialog = false,
})
builder
是一个WidgetBuilder类型的回调函数,它的作用是构建路由页面的具体内容,返回值是一个widget。我们通常要实现此回调,返回新路由的实例。settings
包含路由的配置信息,如路由名称、是否初始路由(首页)。maintainState
:默认情况下,当入栈一个新路由时,原来的路由仍然会被保存在内存中,如果想在路由没用的时候释放其所占用的所有资源,可以设置maintainState
为false。fullscreenDialog
表示新的路由页面是否是一个全屏的模态对话框,在iOS中,如果fullscreenDialog
为true
,新页面将会从屏幕底部滑入(而不是水平方向)。如果想自定义路由切换动画,可以自己继承PageRoute来实现。
(2)Navigator
Navigator
是一个路由管理的widget,它通过一个栈来管理一个路由widget集合。通常当前屏幕显示的页面就是栈顶的路由。Navigator
提供了一系列方法来管理路由栈,在此我们只介绍其最常用的两个方法:
Future
对象,用以接收新路由出栈(即关闭)时的返回数据。result
为页面关闭时返回给上一个页面的数据。 Navigator
还有很多其它方法,如Navigator.replace
、Navigator.popUntil
等,详情请参考API文档或SDK源码注释,在此不再赘述。
main.dart当中完整的代码如下所示:
/*
* 此行代码作用是导入了Material UI组件库。
* Material是一种标准的移动端和web端的视觉设计语言, Flutter默认提供了一套丰富的Material风格的UI组件。
* */
import 'package:flutter/material.dart';
/*
*与C/C++、Java类似,Flutter 应用中main函数为应用程序的入口,main函数中调用了,runApp 方法,
* 它的功能是启动Flutter应用,它接受一个Widget参数,在本示例中它是MyApp类的一个实例,该参数代表Flutter应用。
* main函数使用了(=>)符号,这是Dart中单行函数或方法的简写。
* */
void main() => runApp(MyApp());
/*
* MyApp类代表Flutter应用,它继承了 StatelessWidget类,这也就意味着应用本身也是一个widget。
* 在Flutter中,大多数东西都是widget,包括对齐(alignment)、填充(padding)和布局(layout)。
* Flutter在构建页面时,会调用组件的build方法,widget的主要工作是提供一个build()方法来描述
* 如何构建UI界面(通常是通过组合、拼装其它基础widget)。
* MaterialApp 是Material库中提供的Flutter APP框架,通过它可以设置应用的名称、主题、语言、首页及路由列表等。
* MaterialApp也是一个widget。
* home 为Flutter应用的首页,它也是一个widget。
*
* */
class MyApp extends StatelessWidget {
// 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,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
/*
* MyHomePage 是应用的首页,它继承自StatefulWidget类,表示它是一个有状态的widget(Stateful widget)。
* 现在,我们可以简单认为Stateful widget 和Stateless widget有两点不同:
* 1、Stateful widget可以拥有状态,这些状态在widget生命周期中是可以变的,而Stateless widget是不可变的。
* 2、Stateful widget至少由两个类组成:
* (1)一个StatefulWidget类。
* (2)一个 State类; StatefulWidget类本身是不变的,但是 State类中持有的状态在widget生命周期中可能会发生变化。
* _MyHomePageState类是MyHomePage类对应的状态类。和MyApp 类不同, MyHomePage类中并没有build方法,
* 取而代之的是,build方法被挪到了_MyHomePageState方法中。
* */
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
//计算器变量,是保存屏幕右下角带“➕”号按钮点击次数的状态。
int _counter = 0;
/*
* 计算器自增函数
* 当按钮点击时,会调用此函数,该函数的作用是先自增_counter,
* 然后调用setState 方法。setState方法的作用是通知Flutter框架,有状态发生了改变,
* Flutter框架收到通知后,会执行build方法来根据新的状态重新构建界面,
* Flutter 对此方法做了优化,使重新执行变的很快,所以你可以重新构建任何需要更新的东西,而无需分别去修改各个widget。
* */
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
/*
* 构建UI界面的逻辑在build方法中,当MyHomePage第一次创建时,_MyHomePageState类会被创建,
* 当初始化完成后,Flutter框架会调用Widget的build方法来构建widget树,最终将widget树渲染到设备屏幕上。
* */
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
/*
* Scaffold 是 Material库中提供的一个widget, 它提供了默认的导航栏、标题和包含主屏幕widget树的body属性。
* widget树可以很复杂。
* */
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
/*
* body的widget树中包含了一个Center widget,Center 可以将其子widget树对齐到屏幕中心,
* Center 子widget是一个Column widget,Column的作用是将其所有子widget沿屏幕垂直方向依次排列,
* 此例中Column包含两个 Text子widget,第一个Text widget显示固定文本 “You have pushed the button this many times:”,
* 第二个Text widget显示_counter状态的数值。
* */
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
FlatButton(
child: Text("open new route"),
textColor: Colors.blue,
onPressed: () {
//导航到新路由
Navigator.push( context,
new MaterialPageRoute(builder: (context) {
return new NewRoute();
}));
},
),
],
),
),
/*
* floatingActionButton是页面右下角的带“➕”的悬浮按钮,它的onPressed属性接受一个回调函数,
* 代表它本点击后的处理器,本例中直接将_incrementCounter作为其处理函数。
* */
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class NewRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("New route"),
),
body: Center(
child: Text("This is new route"),
),
);
}
}