Dart是谷歌开发的计算机编程语言,后来被Ecma (ECMA-408)认定为标准 [1] 。它被用于web、服务器、移动应用 [2] 和物联网等领域的开发。它是宽松开源许可证(修改的BSD证书)下的开源软件。 Dart是面向对象的、类定义的、单继承的语言。它的语法类似C语言,可以转译为JavaScript,支持接口(interfaces)、混入(mixins)、抽象类(abstract classes)、具体化泛型(reified generics)、可选类型(optional typing)和sound type system 。 发布 Dart亮相于2011年10月10日至12日在丹麦奥尔胡斯举行的GOTO大会上 [5] 。该项目由Lars bak和kasper lund创建。 标准化 Ecma国际组织组建了技术委员会TC52 [6] 来开展Dart的标准化工作,并且在Dart可以编译为标准JavaScript的情况下,它可以在任何现代浏览器中有效地工作。Ecma国际组织于2014年7月第107届大会批准了Dart语言规范第一版,并于2014年12月批准了第二版 [7] 。 Flutter 2015年5月Dart开发者峰会上,亮相了基于Dart语言的移动应用程序开发框架Sky [8-9] ,后更名为Flutter。 新版本 2018年2月,Dart2成为强类型语言 [10] 。 hello world例子 在终端打印字符串‘Hello World!’ 123 main() { print(‘Hello World!’); } 计算斐波那契数列 123456 int fib(int n) => (n > 2) ? (fib(n - 1) + fib(n - 2)) : 1; void main() { print(‘fib(20) = ${fib(20)}’); } 一个简单的类 计算两点距离 1234567891011121314151617181920212223242526272829303132 // 引入math库以访问sqrt函数 import ‘dart:math’ as math; // 创建类Point. class Point { // Final变量一经定义不可改变 // 创建分别代表x、y轴的距离变量 final num x, y; // 在构造方法中以语法糖快捷地设置实例变量 Point(this.x, this.y); // 一个带有初始化列表的命名构造方法 Point.origin() : x = 0, y = 0; // 计算两点距离的方法 num distanceTo(Point other) { var dx = x - other.x; var dy = y - other.y; return math.sqrt(dx * dx + dy * dy); } // 重载运算符 Point operator +(Point other) => new Point(x + other.x, y + other.y); }
// 所有的Dart程序都以main()函数作为入口 void main() { // 实例化两个点 var p1 = new Point(10, 10); var p2 = new Point.origin(); // 计算两点距离 var distance = p1.distanceTo(p2); print(distance); } 异步并发示例 使用了Isolate 123456789101112131415161718192021222324252627282930313233 import ‘dart:async’; import ‘dart:isolate’;
main() async { var receivePort = new ReceivePort(); await Isolate.spawn(echo, receivePort.sendPort); // 'echo’发送的第一个message,是它的SendPort var sendPort = await receivePort.first; var msg = await sendReceive(sendPort, “foo”); print(‘received $msg’); msg = await sendReceive(sendPort, “bar”); print(‘received $msg’); } /// 新isolate的入口函数 echo(SendPort sendPort) async { // 实例化一个ReceivePort 以接收消息 var port = new ReceivePort(); // 把它的sendPort发送给宿主isolate,以便宿主可以给它发送消息 sendPort.send(port.sendPort); // 监听消息 await for (var msg in port) { var data = msg[0]; SendPort replyTo = msg[1]; replyTo.send(data); if (data == “bar”) port.close(); } } /// 对某个port发送消息,并接收结果 Future sendReceive(SendPort port, msg) { ReceivePort response = new ReceivePort(); port.send([msg, response.sendPort]); return response.first; }