前面文章使用Android Studio创建的Flutter HelloWorld 程序实际上是一个简单的计数器,本文将仔细分析一下这个计数器Demo的源码,让读者对Flutter应用程序结构有个基本了解。
在这个案例中,主要Dart代码在 lib/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,
),
],
),
),
/*
* floatingActionButton是页面右下角的带“➕”的悬浮按钮,它的onPressed属性接受一个回调函数,
* 代表它本点击后的处理器,本例中直接将_incrementCounter作为其处理函数。
* */
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
案例的运行效果如图所示。
该计数器示例中,每点击一次右下角带“➕”号的悬浮按钮,屏幕中央的数字就会加1。
现在,我们将整个流程串起来:当右下角的floatingActionButton按钮被点击之后,会调用_incrementCounter
,在_incrementCounter
中,首先会自增_counter
计数器(状态),然后setState
会通知Flutter框架状态发生变化,接着,Flutter会调用build
方法以新的状态重新构建UI,最终显示在设备屏幕上。
进一步讨论:为什么要将build方法放在State中,而不是放在StatefulWidget中?
现在,我们回答之前提出的问题,为什么build()
方法在State(而不是StatefulWidget)中 ?这主要是为了开发的灵活性。如果将build()
方法在StatefulWidget中则会有两个问题:
(1)状态访问不便。
试想一下,如果我们的Stateful widget 有很多状态,而每次状态改变都要调用build
方法,由于状态是保存在State中的,如果将build
方法放在StatefulWidget中,那么构建时读取状态将会很不方便,试想一下,如果真的将build
方法放在StatefulWidget中的话,由于构建用户界面过程需要依赖State,所以build
方法将必须加一个State
参数,大概是下面这样。
Widget build(BuildContext context, State state){
//state.counter
...
}
这样的话就只能将State的所有状态声明为公开的状态,这样才能在State类外部访问状态,但将状态设置为公开后,状态将不再具有私密性,这样依赖,对状态的修改将会变的不可控。将build()
方法放在State中的话,构建过程则可以直接访问状态,这样会很方便。
(2)继承StatefulWidget不便
例如,Flutter中有一个动画widget的基类AnimatedWidget
,它继承自StatefulWidget
类。AnimatedWidget
中引入了一个抽象方法build(BuildContext context)
,继承自AnimatedWidget
的动画widget都要实现这个build
方法。现在设想一下,如果StatefulWidget
类中已经有了一个build
方法,正如上面所述,此时build
方法需要接收一个state对象,这就意味着AnimatedWidget
必须将自己的State对象(记为_animatedWidgetState)提供给其子类,因为子类需要在其build
方法中调用父类的build
方法,代码可能如下:
class MyAnimationWidget extends AnimatedWidget{
@override
Widget build(BuildContext context, State state){
//由于子类要用到AnimatedWidget的状态对象_animatedWidgetState,
//所以AnimatedWidget必须通过某种方式将其状态对象_animatedWidgetState
//暴露给其子类
super.build(context, _animatedWidgetState)
}
}
这样很显然是不合理的,因为:
(1) AnimatedWidget
的状态对象是AnimatedWidget
内部实现细节,不应该暴露给外部。
(2)如果要将父类状态暴露给子类,那么必须得有一种传递机制,而做这一套传递机制是无意义的,因为父子类之间状态的传递和子类本身逻辑是无关的。
综上所述,可以发现,对于StatefulWidget,将build
方法放在State中,可以给开发带来很大的灵活性。
参考资源:https://book.flutterchina.club/