解析Flutter项目main.dart源码
经过本专栏的第一篇博文之后,相信大家对于Flutter的易开发性以及部署开发环境都有了一定的了解,那么今天我们主要接着上一篇的博文讲解,为什么main.dart的代码显示了上篇博文的界面,所以我们先来一步一步分析main.dart源码:
void main() => runApp(MyApp());
首先,我们打开main.dart文件之后,最上面的代码就是这一段,而void main()就是程序的入口函数,不管是学或C还是Java的都应该一眼就能看出来该函数的意思。
MyApp解析
接着是一段继承至StatelessWidget的MyApp类,代码如下:
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'), ); } }
这个类就相当与用Java编写Android时的Application类,StatelessWidget表示无状态控件(第三篇专门讲解dart语言),MaterialApp可以理解为ui的风格,而其中theme就是主题,比如primarySwatch表示主题色调,上面颜色为blue。
home: MyHomePage(title: 'Flutter Demo Home Page')
这段代码代表主页,主页的标题就是Flutter Demo Home Page,如下图所示:
MyHomePage 解析
既然有MyHomePage这个类,那么当然就有其实现,所以接下来的代码就是其MyHomePage类:
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(); }
它继承至StatefulWidget,StatefulWidget与StatelessWidget相反,是一个有状态的控件,如果你的页面需要动态的更新UI,那么就必须继承这个StatefulWidget有状态的控件,相反,如果你只是静态的展示图片,文字等,就继承至StatelessWidget无状态控件就行。
MyHomePage({Key key, this.title}) : super(key: key);
接着就是这个构造函数,其中的title就是通过上面的MyHomePage(title: ‘Flutter Demo Home Page’)赋值的,而且只能赋值一次,因为他的类型为final String。
_MyHomePageState createState() => _MyHomePageState();
接下来就是上面这段代码,这里可以简单的理解为所有实现有状态控件StatefulWidget的类都必须重写该方法,而前面的“_”在dart语言中代表私有,类似于Java中的private,只能内部访问。
_MyHomePageState 解析
接着main.dart文件就是如下代码(这也是主页显示的详细控件代码集):
class _MyHomePageState extends State<MyHomePage> { int _counter = 0; 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++; }); } @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. 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: 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 a 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: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
首先,我们看到该类定义了一个整形变量int _counter = 0;就是下图中点加号操作的变量,如下图所示:
接着就是一个私有的自增方法,用于点击按钮后,增加上面的整形变量值的操作(_counter++表示自增):
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++; }); }
在接下来的代码就是我们主页的详细布局控件,详细代码如下:
@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. 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: 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 a 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: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); }
其中Scaffold可以看作是Material Design中的一个模板,通过它你可以定义appBar,body,drawer等控件。
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), ),
上面这段代码就是定义标题栏的,可以看到这里定义了标题栏的标题,就是MyHomePage刚传入进入的标题,widget其实就是MyHomePage。
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 a 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: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ),
紧接着就是body代码,相当于HTML中的内容,也相当于主页控件的内容,body:center代码内容居中,其中child定义的控件层级,Column代表一行,那么顾名思义Row就表示一列。
mainAxisAlignment: MainAxisAlignment.center,
这段代码,表示child内部控件也居中显示(mainAxisAlignment翻译成中文就是主轴对准的意思),children: 表示子控件,是一个List类型。
Text( 'You have pushed the button this many times:', ),
其中有一个文本,文本的内容是“You have pushed the button this many times:”
Text( '$_counter', style: Theme.of(context).textTheme.display1, ),
接着又是一个文本控件,显示开头类定义的一个私有的整形变量_counter,这里引用的方式与jQuery很像,其样式为style: Theme.of(context).textTheme.display1。
floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods.
最后是一个自增的浮动按钮,在Java编写的Android程序中同样也有floatingActionButton控件,详细这里很好理解,这里定义了点击该按钮的操作方法onPressed:为上面自增的函数_incrementCounter,tooltip代表长按按钮显示的文字效果,这里为英文的自增。接着就是这个按钮的图标为child: Icon(Icons.add)。
以上就是main.dart的全部的代码,对于初学者来说,博主觉得有必要先理解源代码的意思,然后在学习dart语言,这样看起来就比较容易多了。