本篇我们通过Flutter的HelloWorld,来了解一个Flutter项目的结构。使用Android Studio新建一个Flutter项目(第一次创建需要联网下载一些依赖),稍作等待后我们可以看到如下的文件目录。
我们知道Flutter是可以在Android和IOS跨平台运行的,因此目录下有Android和IOS两个目录。我们只看Android的目录,里面和其它Android项目十分相似,只是它只有一个MainActivity,而这个Activity也只有一个View。程序运行时,不是像传统的Android程序那样渲染页面,而是通过Flutter自己的引擎来渲染,这样页面绘制的速度是比原生快的,而且也实现了跨平台的效果。
下面来看一下配置文件,Flutter是用yaml文件配置 ,yaml类似于标准通用标记语言的子集XML的数据描述语言,语法比规则如下:
大小写敏感
缩进代表层级,使用空格,默认2个空格(flutter工具做了处理,tab也可以)
#表示注释内容
: 表示键值对,注意后面要空格
{} 表示键值表
这里我们重点注意的是dependencies和flutter项,程序需要用到的包需要在dependencies下引入,而用到的资源文件需要在flutter下引入,这样才能正常使用,下面我们详细介绍。
Pub(https://pub.dev/ )是Google官方的Dart Packages仓库,类似于node中的npm仓库,android中的jcenter。进去后就可以找到很多开源的包,上面带有Flutter标签的就可以在Flutter项目里使用:
我们将类型选择为Flutter,就可以在上面看到按排名排序的Flutter插件,可以直接在项目里使用,只需在pubspec配置文件里声明即可,声明后直接点击Package get,就像下面这样:
引入后,在要使用的dart文件里引入就可以用了:
import 'package:shared_preferences/shared_preferences.dart';
这里要注意,使用的版本要与Flutter SDK版本一致,在Pub仓库里都有详细的介绍插件的版本与Flutter版本的对应关系。
而如果我们想要引入一个本地的包,包名为pkg1,我们可以通过下面方式依赖:
dependencies:
pkg1:
path: ../../code/pkg1
路径可以是相对的,也可以是绝对的。
和包管理一样,Flutter也使用pubspec.yaml文件来管理应用程序所需的资源:
flutter:
assets:
- assets/my_icon.png
- assets/background.png
assets指定应包含在应用程序中的文件, 每个asset都通过相对于pubspec.yaml文件所在的文件系统路径来标识自身的路径,asset的目录名可以是任意文件夹(在本示例中是assets文件夹)。
对于不同分辨率的图片可以通过asset变体的方式来管理,例如有如下几个不同分辨率的同名图片:
…/my_icon.png
…/2.0x/my_icon.png
…/3.0x/my_icon.png
在使用时只需在配置文件里声明一次my_icon即可,那么这几个名为my_icon的图片都将包含在您的asset bundle中。前者被认为是main asset (主资源),后者被认为是一种变体(variant)。在设备像素比率为1.8的设备上,…/2.0x/my_icon.png 将被选择。对于2.7的设备像素比率,…/3.0x/my_icon.png将被选择。
在需要加载资源时,可以用AssetBundle来加载,例如:
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future loadAsset() async {
return await rootBundle.loadString('assets/config.json');
}
当然这只是一种实现方法,还可以用DefaultAssetBundle.of()在应用运行时来间接加载asset,这里就不详细说了。
好了,终于到了一个Flutter项目的主要内容,我们知道Flutter使用Dart作为其开发语言的,相关文件以.dart作为后缀。作为Flutter的Hello World的是一个计数器程序,了解它可以帮助我们对其有一个基本的认识,下面我们逐行来看:
import 'package:flutter/material.dart';//引入Material UI组件库
//main函数中调用了runApp 方法,它的功能是启动Flutter应用。runApp它接受一个Widget参数,在本示例中它是一个MyApp对象,MyApp()是Flutter应用的根组件。
void main() => runApp(MyApp());
//MyApp类代表Flutter应用,它继承了 StatelessWidget类,这也就意味着应用本身也是一个widget
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
//Flutter在构建页面时,会调用组件的build方法,widget的主要工作是提供一个build()方法来描述如何构建UI界面。
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 是Flutter应用的首页,它继承自StatefulWidget类,表示它是一个有状态的组件(Stateful widget)。
//StatelessWidget通常用来展示哪些数据固定不变的,如果数据会发生改变,我们使用StatefulWidget
class MyHomePage extends StatefulWidget {
//key继承于父类StatefulWidget的key
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;//用于记录按钮点击的总次数
//自增函数
void _incrementCounter() {
//先自增_counter,然后调用setState 方法。
// setState方法的作用是通知Flutter框架,有状态发生了改变,Flutter框架收到通知后,会执行build方法来根据新的状态重新构建界面
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组件库提供的页面脚手架
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),
),
//Center 可以将其子组件树对齐到屏幕中心。
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
//Column的作用是将其所有子组件沿屏幕垂直方向依次排列
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: [
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
//floatingActionButton是页面右下角的带“+”的悬浮按钮,它的onPressed属性接受一个回调函数,代表它被点击后的处理器
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
好了,学习了这些,我们也算对Flutter项目有了一个基本的认识,接下来还要再项目实践中慢慢学习。