Flutter学习笔记之dart Keywords

先见识下dart的最基本特性:

// 定义个方法。
printNumber(num aNumber) {
  print('The number is $aNumber.'); // 在控制台打印内容。   $变量
}

// 这是程序执行的入口。
main() {
  var number = 42; // 定义并初始化一个变量。用var修饰,变量没有初始化之前全都为null
  printNumber(number); // 调用上面定义的方法。
}

Keywords(关键字)认识

  1. abstract
    1)Abstract methods(抽象函数)
    抽象函数是只定义函数接口但是没有实现的函数,由子类来 实现该函数
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();
}
  1. break && continue

使用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();
}
  1. true && false
// 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);
  1. Assert(断言)
    assert 方法的参数可以为任何返回布尔值的表达式或者方法。 如果返回的值为 true, 断言执行通过,执行结束。 如果返回值为 false, 断言执行失败,会抛出一个异常 AssertionError)。
  2. new
    用来创建对象var p1 = new Point(2, 2);
  3. this
    指当前的实例。注意:只有当名字冲突的时候才使用 this。否则的话, Dart 代码风格样式推荐忽略 this。
  4. asis && is!
    是在运行时判定对象 类型的操作符
操作符 解释
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 则会抛出一个异常。

  1. switchdefault && case
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;
}
  1. Final && const
    如果你以后不打算修改一个变量,使用 final 或者 const。 一个 final 变量只能赋值一次;一个 const 变量是编译时常量。 (Const 变量同时也是 final 变量。) 另外,const 关键字不仅仅只用来定义常量。 有可以用来创建不变的值, 还能定义构造函数为 const 类型的,这种类型 的构造函数创建的对象是不可改变的。任何变量都可以有一个不变的值。
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
  1. finallytry && catch
try {
  breedMoreLlamas();
} catch(e) {
  print('Error: $e');  // Handle the exception first.
} finally {                   //必走的方法
  cleanLlamaStalls();  // Then clean up.
}
  1. async && await
    异步,配合使用
checkVersion() async {                   //method
  var version = await lookUpVersion();        //变量
  if (version == expectedVersion) {
    // Do something.
  } else {
    // Do something else.
  }
}
  1. get && set
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);
}
  1. rethrow
    把catch到的exception重新丢出来
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}.');
  }
}
  1. enum
    枚举类型
enum Color {
  red,
  green,
  blue
}
  1. Static

静态变量

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');
}

静态变量在第一次使用的时候才被初始化。
静态函数

扫描二维码关注公众号,回复: 5156038 查看本文章
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

  1. in
var collection = [0, 1, 2];
for (var x in collection) {   //for-in  循环
  print(x);
}

关键字还有nullthrowdeferredoperatordoforpartdynamicifelsereturnimplementsvoidwhilesuperwithyieldlibrary 要么比较简单,或者后续模块里记载喽。

下一篇:dart 内置类型

猜你喜欢

转载自blog.csdn.net/julystroy/article/details/86692609