先见识下dart的最基本特性:
// 定义个方法。
printNumber(num aNumber) {
print('The number is $aNumber.'); // 在控制台打印内容。 $变量
}
// 这是程序执行的入口。
main() {
var number = 42; // 定义并初始化一个变量。用var修饰,变量没有初始化之前全都为null
printNumber(number); // 调用上面定义的方法。
}
Keywords(关键字)认识
abstract class Doer {
// ...Define instance variables and methods...
void doSomething(); // 注意这个; 由;结尾
}
class EffectiveDoer extends Doer {
void doSomething() {
// ...Provide an implementation, so the method is not abstract here...
}
}
2)Abstract classes(抽象类)
abstract 修饰符定义一个 抽象类—一个不能被实例化的类。 抽象类通常用来定义接口, 以及部分实现
// This class is declared abstract and thus
// can't be instantiated.
abstract class AbstractContainer {
// ...Define constructors, fields, methods...
void updateChildren(); // Abstract method.
}
class SpecializedContainer extends AbstractContainer {
// ...Define more constructors, fields, methods...
void updateChildren() {
// ...Implement updateChildren()...
}
// Abstract method causes a warning but
// doesn't prevent instantiation.
void doSomething();
}
使用break终止循环
while (true) {
if (shutDownRequested()) break;
processIncomingRequests();
}
使用continue开始下一个循环
for (int i = 0; i < candidates.length; i++) {
var candidate = candidates[i];
if (candidate.yearsExperience < 5) {
continue;
}
candidate.interview();
}
// Check for an empty string.
var fullName = '';
assert(fullName.isEmpty);
// Check for zero.
var hitPoints = 0;
assert(hitPoints <= 0);
// Check for null.
var unicorn;
assert(unicorn == null);
// Check for NaN.
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);
var p1 = new Point(2, 2);
操作符 | 解释 |
---|---|
as | 类型转换 |
is | 如果对象是指定的类型返回 True |
is! | 如果对象是指定的类型返回 False |
if (emp is Person) { // Type check
emp.firstName = 'Bob';
}
用as上面的就可以转化为
(emp as Person).firstName = 'Bob';
注意: 上面这两个代码效果是有区别的。如果 emp 是 null 或者不是 Person 类型, 则第一个示例使用 is 则不会执行条件里面的代码,而第二个情况使用 as 则会抛出一个异常。
var command = 'OPEN';
switch (command) {
case 'CLOSED':
executeClosed();
break;
case 'PENDING':
executePending();
break;
case 'APPROVED':
executeApproved();
break;
case 'DENIED':
executeDenied();
break;
case 'OPEN':
executeOpen();
break;
default: //默认的情况
executeUnknown();
}
注意:上面的break,如果忘记写,会报ERROR: Missing break causes an exception!!
但是空 case 语句中可以不要 break
var command = 'CLOSED';
switch (command) {
case 'CLOSED': // Empty case falls through.
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
如果你需要实现这种继续到下一个 case 语句中继续执行,则可以 使用 continue 语句跳转到对应的标签(label)处继续执行:
var command = 'CLOSED';
switch (command) {
case 'CLOSED':
executeClosed();
continue nowClosed;
// Continues executing at the nowClosed label.
nowClosed:
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
final name = 'Bob'; // Or: final String name = 'Bob';
// name = 'Alice'; // Uncommenting this causes an error
const bar = 1000000; // Unit of pressure (dynes/cm2)
const atm = 1.01325 * bar; // Standard atmosphere
try {
breedMoreLlamas();
} catch(e) {
print('Error: $e'); // Handle the exception first.
} finally { //必走的方法
cleanLlamaStalls(); // Then clean up.
}
checkVersion() async { //method
var version = await lookUpVersion(); //变量
if (version == expectedVersion) {
// Do something.
} else {
// Do something else.
}
}
class Rectangle {
num left;
num top;
num width;
num height;
Rectangle(this.left, this.top, this.width, this.height);
// Define two calculated properties: right and bottom.
num get right => left + width;
set right(num value) => left = value - width;
num get bottom => top + height;
set bottom(num value) => top = value - height;
}
main() {
var rect = new Rectangle(3, 4, 20, 15);
assert(rect.left == 3);
rect.right = 12;
assert(rect.left == -8);
}
final foo = '';
void misbehave() {
try {
foo = "You can't change a final variable's value.";
} catch (e) {
print('misbehave() partially handled ${e.runtimeType}.');
rethrow; // Allow callers to see the exception.
}
}
void main() {
try {
misbehave();
} catch (e) {
print('main() finished handling ${e.runtimeType}.');
}
}
enum Color {
red,
green,
blue
}
静态变量
class Color {
static const red =
const Color('red'); // A constant static variable.
final String name; // An instance variable.
const Color(this.name); // A constant constructor.
}
main() {
assert(Color.red.name == 'red');
}
静态变量在第一次使用的时候才被初始化。
静态函数
import 'dart:math';
class Point {
num x;
num y;
Point(this.x, this.y);
static num distanceBetween(Point a, Point b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
}
main() {
var a = new Point(2, 2);
var b = new Point(4, 4);
var distance = Point.distanceBetween(a, b);
assert(distance < 2.9 && distance > 2.8);
}
静态函数不再类实例上执行, 所以无法访问 this
var collection = [0, 1, 2];
for (var x in collection) { //for-in 循环
print(x);
}
关键字还有null、throw、deferred、operator 、do、for、part、dynamic 、if、else、return、implements 、void、while、super、with、yield 、library 要么比较简单,或者后续模块里记载喽。
下一篇:dart 内置类型