作为Flutter专属的开发语言(当然Dart不知如此,也可以开发Web和服务端),面对对象、高性能、多端一致、热更新是Dart的优势所在,是Flutter开发必须掌握的语言,也正是Flutter的流行让Dart进入了我的视野。
![ad15d8514810f97dcad2db14368eb2a9.png](https://img-blog.csdnimg.cn/img_convert/ad15d8514810f97dcad2db14368eb2a9.png)
Dart是一门被谷歌定义为专门用于UI的开发语言(Develop with a programming language specialized around the needs of user interface creation),语法与TS、JS类似,但有些许不同。
本文意旨快速浏览一遍Dart的基本语法(Dart 2.8),并不是深入讲解这门语言的各个细节(后续会单独推出每个重点语法的文章)。 如果正巧你是Flutter爱好者或初学者,通过本文你可以快速了解Dart大概使用方式。做到心中有数,然后再决定自己是否还要继续学习下去。
希望能让你对Dart语言产生感兴趣,而不仅仅是为了应付工作。
Hello World
每一个Dart应用都有且唯一的入口方法 main()。使用 print() 函数进行打印。
// 唯一入口 mainvoid main() { print('Hello, World!');}
变量
作为类型安全的强类型语言,Dart也不需要每次都声明变量类型,程序可以自动推断。 能存放在变量中的内容都是对象,初始值都为null
// 定义类型String strvar = "a";int intvar = 12;int undef; // null// 自动推断var name = 'abc';var year = 12345;var scale = 0.5;var list = ['a', 'b', 'c', 'd'];// JS中的对象在Dart中为Map类型var image = { 'name': 'abc', 'age': '23'};// 常量const a = 123; // 编译时常量final b = 456; // 运行时常量var c = "a = $a"; // 与ES6中的反引号很像,但是变量不需要{}包裹
流程控制
三元表达式相关:
// a为true,则res1=b,否则res1=cvar res1 = a ? b : c;// d为null,则res2=1,否则res2=d,和Js中的 || 用法很像var res2 = d ?? 1;
常用判断与循环,和Js类似,这里就不过多阐述了:
if (a >= 100) { print('>= 100');} else if (a >= 60) { print('>= 60');} else { print('else');}for (var item in myArray) { print(item);}for (int i = 1; i
函数
Dart 推荐为每一个函数的入参和返回值声明类型:
int plus(int a, int b) { return a + b;}var result = plus(1, 2);
Dart 也有箭头函数 () => {},和 ES6 也非常相似:
int plus(int a, int b) => a + b;
Dart函数入参有两种形式:必填、可选。必填在前,可选在后。
位置参数 使用 {} 定义
// 命名参数定义时用{}讲参数包裹int plus({int a, int b}) => a + b;// 调用时指定参数名var c = plus(a: 1, b: 2);
可选参数 使用 [] 定义,
int plus(int a, [int b]) { if(b != null){ return a + b; } return a;}var c = plus(1); // 1
可选参数默认值 =
int plus(int a = 1, [int b = 2]) => a + b;
模块化
使用 import 关键字引用其他库或文件:
// 引用核心库import 'dart:math';// 引用其他库import 'package:test/test.dart';// 引用文件import 'path/to/my_other_file.dart';
类
.. 对同一对象进行操作
class Person { String name; int age = 0; // 直接将参数赋值给类中的属性 Person(this.name, this.age); Person(var n): name = n; Person.birth(String n): this(n, 0); // get bool get adult () => age > 18; talk () => print("我叫: $name, 年龄: $age"); void showName () { print("$name"); }}Person tom = Person("Tom", 13);var amy = Person.birth("Amy");amy.talk();
单继承
类最多只能继承一个父类:
class Student extends Person { String schoolName; Student(String name, int age, this.schoolName):super(name, age);}
混入
虽然只能单继承,但是利用混入语法Mixin可以轻松实现代码的复用:
class Talk { String keywords = "hello world"; void talk() { print('Person can talk!'); }}
将一个类混入只需要使用with关键字
class Student extends Person with Talk { // ···}
这样Student类就拥有了 keywords 字段和 Talk方法。
同步(解决异步回调地狱)
Dart 中有一个名为 Future 的类,它和Js中的Promise非常类似: 在异步事件完成后将结果通过 then 方法返回; 和Js更为相似的是,Dart同样拥有 async 和 await 关键字,熟悉Js的同学对这两个单词一定非常熟悉。 在Es8中,他们是将Promise转为同步写法的语法糖,在Dart中则是将Future转为同步的语法糖。
不过和Js的声明方式略有不同:
const oneSecond = Duration(seconds: 1);// ···Future printWithDelay(String message) async { await Future.delayed(oneSecond); print(message);}The method above is equivalent to:Future printWithDelay(String message) { return Future.delayed(oneSecond).then((_) { print(message); });}
下面的例子里我们使用 async 和 awai 让代码更有可读性。
Future createDescriptions(Iterable objects) async { for (var object in objects) { try { var file = File('$object.txt'); if (await file.exists()) { var modified = await file.lastModified(); print( 'File for $object already exists. It was modified on $modified.'); continue; } await file.create(); await file.writeAsString('Start describing $object in this file.'); } on IOException catch (e) { print('Cannot create description for $object: $e'); } }}
异常
在Js中,经常可以看到使用try catch来捕获async的异常情况,在Dart中的使用方式也很类似:
try { // throw抛出异常 throw Exception("接口错误");} on IOException catch (e) { print('错误信息:$e');} finally { // 与Js中的finally一致}