Google和其他地方的一些开发者使用Dart语言为Android、iOS和web构建高质量,关键任务的应用程序,针对客户端开发的特点,Dart非常适合移动和Web应用程序。
Dart语言的特性
Productive(丰富多产的)
Dart’s syntax is clear and concise, its tooling simple yet powerful. Sound typing helps you to identify subtle errors early. Dart has battle-hardened core libraries and an ecosystem of thousands of packages.
Dart的语法清晰明了,工具简单但功能强大。Sound typing有助于早期识别细微的错误。Dart拥有久经沙场的核心库和数以千计的生态系统。
Fast(快速的)
Dart provides optimizing ahead-of-time compilation to get predictably high performance and fast startup across mobile devices and the web.
Dart提供提前优化编译,以在移动设备和Web上获得可预测的高性能和快速启动。
Portable(可移植的)
Dart compiles to ARM and x86 code, so that Dart mobile apps can run natively on iOS, Android, and beyond. For web apps, Dart transpiles to JavaScript.
Dart可编译成ARM和X86代码,这样Dart移动应用程序可以在iOS、Android和其他地方运行。对于Web应用程序,DART可编译成JavaScript。
Approachable(亲切的)
Dart is familiar to many existing developers, thanks to its unsurprising object orientation and syntax. If you already know C++, C#, or Java, you can be productive with Dart in just a few days.
Dart对于许多现有的开发人员来说是熟悉的,这得益于其令人惊讶的对象定位和语法。如果你已经知道C++,C语言,或者Java,你可以在短短几天内用Dart来开发。
Reactive(反应式的)
Dart is well-suited to reactive programming, with support for managing short-lived objects—such as UI widgets—through Dart’s fast object allocation and generational garbage collector. Dart supports asynchronous programming through language features and APIs that use Future and Stream objects.
Dart非常适合于反应式编程,支持通过Dart的快速对象分配和代垃圾收集器来管理诸如UI小部件之类的短命对象。Dart通过使用未来和流对象的语言特征和API支持异步编程。
Dart语法简介
关于Dart的语法,如果你熟悉Java,应该很快能掌握Dart,官网上对于Dart的语法也有详细介绍,不过是全英文的,如果对英文没有什么阅读障碍,可以直接移步官方文档。
为了了解Dart的语法基础,这里我们使用Android Studio作为开发工具(你也可以使用dartpad来运行代码,它是一个基于浏览器的dart运行时环境),如果你按照上一篇文章中搭建好了Flutter开发环境,那么可以直接在Android Studio中新建Flutter项目,如下图所示:
新创建的Flutter项目,Dart代码主要在lib/main.dart
文件中,由于本篇主要是讲Dart的语法,故暂时不看main.dart文件,在lib目录下我们创建一个新的.dart
文件demo.dart
,如下图所示:
在新建的demo.dart
文件中,输入如下代码:
// Define a function.
printInteger(int aNumber) {
print(‘The number is $aNumber.’); // Print to console.
}
// This is where the app starts executing.
main() {
var number = 42; // Declare and initialize a variable.
printInteger(number); // Call a function.
}
然后在代码编辑区域鼠标右键,选择Run demo.dart
,即可运行一个最简单的dart程序,如下图所示:
运行后控制台输出如下图:
关于上面的代码,有如下几点需要说明:
-
Dart中单行注释使用
//
,Dart同时支持多行注释和文档注释,可以点击这里查看更多 -
int
是Dart中的一种数据类型,同时还有其他的一些内置数据类型如String
List
bool
等 -
控制台输出使用
print
语句 -
字符串使用单引号或双引号均可,如’hello’, “hello”
-
字符串插入可以使用类似
$name
或${name}
的语法,比如下面的代码:
var name = ‘zhangsan’;
print(“hello, I am n a m e " ) ; i n t a = 10 , b =