Dart 开发iOS 开发 程序员

Dart 语言简易教程(一)

2016-08-30  本文已影响6002人  you的日常

在 InteIIiJ IDEA 中搭建 Dart 的开发环境: http://www.jianshu.com/p/fa275a08b083

Dart 语言简易教程(一)

一个简单的dart 程序

// Define a function.
printNumber(num 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.
  printNumber(number); // Call a function.
}

从这个程序里面我们可以看到如下的东西:

按照Dart 的编程规范,使用2个空格来缩进。
这一点与Python 语言建议的4个空格不一样。

一些重要的概念

关键字

Dart 语言提供的关键字如下表所示:

1 2 3 4 5
abstract continue false new this
as default final null throw
assert deferred finally operator true
async do for part try
async dynamic get rethrow typedef
await else if return var
break enum implements set void
case export import static while
catch external in super with
class extends is switch yield
const factory library sync yield

变量(Variable

变量赋值的例子

// The variable called name contains a reference to a String object with a value of “Bob”.
var name = 'Bob';

默认值

没有初始化的变量都会被赋予默认值 null.
即使是数字也是如此, 因为在Dart 中数字也是一个对象。

int lineCount;
assert(lineCount == null);
// Variables (even if they will be numbers) are initially null.
```language

Note: The assert() call is ignored in production mode. In checked mode, assert(condition) throws an exception unless condition is true.

可选类型

也可以在定义的时候指定变量的类型。

String name = 'Bob';

指定数据类型可以更好的辨明自己的使用意图,编译器和IDE 工具可以根据这些类型信息来做检查,更早的发现问题。
如前文所说,通过指定类型,也可以减少编译和运行时间。

常量和固定值

  1. 如果定义的变量不会变化,可以使用finalconst来指明。
    也可以使用finalconst来代替类型声明。

    • final的值只能被设定一次。
    • const 是一个编译时的常量。( Const variables are implicitly final.)
    final name = 'Bob'; // Or: final String name = 'Bob';
    // name = 'Alice';  // Uncommenting this causes an error
    
  2. 通过对const类型做四则运算将自动得到一个const类型的值。

const bar = 1000000;       // Unit of pressure (dynes/cm2)
const atm = 1.01325 * bar; // Standard atmosphere
```language
  1. 可以通过const来创建常量的值
    就是说const[] 本身是构造函数。
// Note: [] creates an empty list.
// const [] creates an empty, immutable list (EIA).
var foo = const [];   // foo is currently an EIA.
final bar = const []; // bar will always be an EIA.
const baz = const []; // baz is a compile-time constant EIA.
// You can change the value of a non-final, non-const variable,
// even if it used to have a const value.
foo = [];
// You can't change the value of a final or const variable.
// bar = []; // Unhandled exception.
// baz = []; // Unhandled exception.
上一篇下一篇

猜你喜欢

热点阅读