flutter基础教程
Flutter是谷歌的移动UI框架,可以快速在iOS和Android上构建高质量的原生用户界面。 Flutter可以与现有的代码一起工作。在全世界,Flutter正在被越来越多的开发者和组织使用,并且Flutter是完全免费、开源的。
flutter官网:flutter.dev/
flutter的产生背景
根据第43次《中国互联网络发展状况统计报告》,截至2018年12月,我国网民规模达8.29亿,我国手机网民规模达8.17亿,网民通过手机接入互联网的比例高达98.6%,移动互联网早已成为各大公司角逐的主战场;但是移动端不像pc一样,有w3c标准,只有JavaScript一种语言。面对纷繁复杂的操作系统,怎样避免同一界面或者功能需要重复开发多遍也成了大家关注的重点。
flutter同类型框架对比
react native
- 原生app里面用js来调用原生组件.
- 运行UI较为流畅,集成原生组建较为容易,出现时间长,大公司支持,生态丰富.
- 初次学习成本较高.js是单线程运行,高频率调用会造成线程卡顿,从而导致UI卡顿,无法很好支持长列表,调试可能需要使用chrome浏览器等.
Cordova
- 原生app里面用自定义webview来运行js代码.
- 做出来的效果差,但是开发学习成本稍低
flutter
- 原生app里面用自定义引擎来运行跨平台代码.
- 像游戏引擎一样,支持iOS,Android平台,UI流畅,甚至于用它开发游戏也是可以的.Google对与原生UI的支持也比较给力.直接可以在iDE上查看log无需浏览
- 初次学习成本高.生态不够丰富,仍然需要开发者努力丰富.原生组件集成比react native成本高
对比
- UI流畅度: webApp类的框架 < RN < flutter
- 原生功能的生态支持: webApp类的框架 < flutter < RN
- 未来的预期: webApp类的框架 < RN < flutter
相关文章推荐:blog.csdn.net/ZuoYueLiang…
安装flutter开发环境
mac下安装
系统要求:
- 操作系统:macOS(64位)
- 磁盘空间:700 MB(不包括Xcode或Android Studio的磁盘空间)
步骤:
-
下载所需版本安装包
-
解压安装包到你想安装的目录,如:
cd ~/development unzip ~/Downloads/flutter_macos_v1.7.8+hotfix.4-stable.zip -
配置环境变量,当前终端窗口环境配置:
export PATH="$PATH:`pwd`/flutter/bin"永久环境变量:
- 确定您Flutter SDK的目录,您将在步骤3中用到。
- 打开(或创建)
$HOME/.bash_profile. 文件路径和文件名可能在您的机器上不同. - 添加以下行并更改
[PATH_TO_FLUTTER_GIT_DIRECTORY]为克隆Flutter的git repo的路径:
export PUB_HOSTED_URL=https://pub.flutter-io.cn //国内用户需要设置 export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn //国内用户需要设置 export PATH=PATH_TO_FLUTTER_GIT_DIRECTORY/flutter/bin:$PATH注意:
PATH_TO_FLUTTER_GIT_DIRECTORY为你flutter的路径,比如“~/document/code”export PATH=~/document/code/flutter/bin:$PATH- 运行
source $HOME/.bash_profile刷新当前终端窗口. - 通过运行
flutter/bin命令验证目录是否在已经在PATH中:
echo $PATH注意: 如果你使用的是zsh,终端启动时
~/.bash_profile将不会被加载,解决办法就是修改~/.zshrc,在其中添加:source ~/.bash_profile -
运行 flutter doctor
运行以下命令查看是否需要安装其它依赖项来完成安装:
flutter doctor通过检查命令行输出以获取可能需要安装的其他软件或进一步需要执行的任务(以粗体显示)
例如:
[-] Android toolchain - develop for Android devices • Android SDK at /Users/obiwan/Library/Android/sdk ✗ Android SDK is missing command line tools; download from https://goo.gl/XxQghQ • Try re-installing or updating your Android SDK, visit https://flutter.io/setup/#android-setup for detailed instructions.
安装开发工具
理论上,任何文本编辑器都可以用来开发 Flutter 应用,但推荐的开发工具是 Android Studio、IntelliJ 以及 VS Code。因为在这些开发工具上,可以安装官方的 Flutter 和 Dart 插件(Flutter 插件用于支持 Flutter 的运行、调试、热重载等功能,而 Dart 插件则提供了代码的输入校验、代码补全等功能),得到更好的开发体验。
如果你打算开发 iOS 应用,则还需要安装 Xcode。
安装常见问题及解决办法
问题1:
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun Doctor summary (to see all details, run flutter doctor -v):
解决办法:
xcode-select --install
问题2:
-bash: brew: command not found
解决办法:
安装brew的方法:
- brew.sh/index_zh-cn…
- /usr/bin/ruby -e "$(curl -fsSL raw.githubusercontent.com/Homebrew/in…)"
配置命令行科学上网教程:blog.csdn.net/pansanday/a…
Dart语法相关
Dart 基础语法学习教程:
官网:dart.dev
中文网:dart.goodev.org
Dart语法快速入门:
web开发者快速入门
对比web端开发的区别:
项目创建
打开Android Studio选择 Start a new Flutter project,或者通过菜单栏的 File > New > New Flutter Project,一个新的 Flutter 项目就创建好了。
项目结构
├── README.md
├── android // android工程文件
├── ios // ios工程文件
├── lib
│ └── main.dart // 入口文件
├── pubspec.lock
├── pubspec.yaml // 包管理文件
└── test
└── widget_test.dart // 测试文件
创建好的项目里面包含了 android 和 ios 两个文件夹,它们是标准的 Android 和 iOS 项目。我们的 Flutter 代码,存放在 lib 文件夹里。 main.dart为项目入口文件。
Main.dart
import 'package:flutter/material.dart';
void main() => runApp(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'),
);
}
}
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<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 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.
);
}
}
pubspec.yaml文件
pubspec.yaml 类似于与 node.js 的 package.json. 用于描述项目的基本信息、依赖的模块等.
同样的, 就像 node.js 的 package-lock.json, Flutter 也有类似的包锁文件, 叫做 pubspec.lock.
pubspec.yaml 也会像 package.json 一样区分 dependencies 和 dev_dependencies .
name: CNode # 项目名称, 编译后会作为App的名字
description: A new Flutter project. # 项目描述
dependencies: # 项目依赖
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
dev_dependencies: # 开发依赖
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- images/picture.png
通过flutter packages get命令,即可根据 pubspec.yaml 文件安装依赖包。
flutter 常用命令
常用命令:
flutter create <output directory> 创建项目
flutter run [options] 运行项目
使用: flutter <command> [arguments]
全局选项:
-h, --help 打印帮助信息
-v, --verbose 动态日志
-d, --device-id 目标设备 ID 或名称
--version 查看命令版本
--suppress-analytics 禁止分析报告
--bug-report 提交 bug
可用的命令:
analyze 分析 dart 代码
attach 附加应用到连接中的设备
build 构建应用
channel 列出或者切换通道
clean 删除 build/ 文件夹
config 配置 flutter
create 创建项目
devices 列出已连接的设备
doctor 检查 flutter 信息
drive Runs Flutter Driver tests for the current project.
emulators 列出可用的设备
format 格式化 Dart 文件
fuchsia_reload 热加载
help 显示帮助信息
install 在连接的设备中安装 app
logs 显示正在运行的应用的日志
packages 包
precache Populates the Flutter tool's cache of binary artifacts.
run 运行应用
screenshot 为应用截图
stop 停止运行
test Run Flutter unit tests for the current project.
trace Start and stop tracing for a running Flutter app.
upgrade 更新 flutter
flutter组件
flutter 里最重要的一个概念是 Widget,在原生开发里面,我们可能会在界面上区分,这是一个 View,这是一个 Layout,这是一个 View Controller。但在 Flutter 里面,它们全都属于一个统一的模型 Widget。可以说,在 Flutter 界面中,所有东西都是 Widget。
组件分类
使用页面跳转
在 Flutter 中,我们使用 Navigator 来管理页面跳转,eg:
Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return NewPage();
}));
使用本地图片
在flutter中,我们使用本地图片的时候需要在pubspec.yaml中配置所需要使用的图片;eg:
assets:
- images/picture.png
然后在Image组件中展示出来。eg:
Image.asset("images/picture.png"))
使用第三方库
在flutter中,我们使用第三方库的时候需要在pubspec.yaml文件中dependencies 下添加配置;eg:
fluro: ^1.4.0
运行flutter packages get命令同步之后就可以使用了。
UI库
- Material组件库,多用于Android
- cupertino组件库,用于ios样式组件
扩展
游戏
开源flutter app
- fluter-go:阿里出品,一个中文的flutter组件展示和讲解app项目
- flutter_wanandroid:一个较为完善的flutter app项目,参考它可以快速搭建项目架构。
- flutter-osc:一个flutter版本的开源中国app。不是官方出品,但也有一定的参考价值。
- zhihu-flutter:一个flutter版本的知乎app。不是官方出品,但也有一定的参考价值。