Dart学习2

76 阅读5分钟

枚举

定义

适合用在常量定义,类型比较很方便。

// 定义颜色枚举值
enum ColorType {
  none,
  red,
  green,
  blue,
}

void main(List<String> args) {
  // 1 接收输入值 red 字符串
  var input = "red";

  // 2 将输入值转换为 ColorType 枚举类型
  var color = ColorType.none;
  if (input == "red") {
    color = ColorType.red;
  } else if (input == "green") {
    color = ColorType.green;
  } else if (input == "blue") {
    color = ColorType.blue;
  }

  // 3 switch 判断,打印输出
  switch (color) {
    case ColorType.red:
      print(ColorType.red);
      break;
    case ColorType.green:
      print(ColorType.green);
      break;
    case ColorType.blue:
      print(ColorType.blue);
      break;
    default:
      print(ColorType.none);
  }
}

使用场景

定义发帖类型 视频 图片 空

enum PostType { video, image, none }

业务中判断

  PostType get type {
    if (detail.type == POST_TYPE_IMAGE) {
      return PostType.image;
    } else if (detail.type == POST_TYPE_VIDEO) {
      return PostType.video;
    } else {
      return PostType.none;
    }
  }

  ...

  if (type == PostType.video && !_hasDetail) {
    playlist.insert(0, VideoMedia(detail));
  }

  ...

  if (type == PostType.video) {
      if (playlist.isEmpty) {
        playlist.add(VideoMedia(detail));
      } else {
        playlist.first.post = detail;
      }
    }
  } finally {
    _isLoading = false;
    if (type == PostType.video && !_hasDetail) getPostList();
  }

注释

单行注释

// Symbol libraryName = new Symbol('dart.core');

多行注释

  /*
   * Symbol
   *
  Symbol libraryName = new Symbol('dart.core');
  MirrorSystem mirrorSystem = currentMirrorSystem();
  LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName);
  libMirror.declarations.forEach((s, d) => print('$s - $d'));
  */

一般用在需要说明 类 函数 功能 输入 输出

文档注释

/// `main` 函数
///
/// 符号
/// 枚举
///
void main() {
  ...
}

类、函数 请用 /// 方式定义,后期导出文档有帮助

函数

定义

int add(int x) {
  return x + 1;
}

// 调用
add(1);

可选参数

int add(int x, [int? y, int? z]) {
  if (y == null) {
    y = 1;
  }
  if (z == null) {
    z = 1;
  }
  return x + y + z;
}

// 调用
add(1, 2);

可选参数 默认值

int add(int x, [int y = 1, int z = 2]) {
  return x + y;
}

调用
int(1, 2);

命名参数 默认值

int add({int x = 1, int y = 1, int z = 1}) {
  return x + y + z;
}

// 调用
int(x: 1, y: 2);

函数内定义

void main(){
  int add(int x){
    return x + x;
  }
  print(add(1));
}

Funcation 返回函数对象

Function makeAdd(int x) {
  return (int y) => x + y;
}

// 调用
var add = makeAdd(1);
print(add(5));

匿名函数

下面代码定义了只有一个参数 item 且没有参数类型的匿名方法。 List 中的每个元素都会调用这个函数,打印元素位置和值的字符串:

const list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
  print('${list.indexOf(item)}: $item');
});

箭头函数 如果只有一个表达式

list.forEach((item) => print('${list.indexOf(item)}: $item'));

作用域

下面是一个嵌套函数中变量在多个作用域中的示例:

bool topLevel = true;

void main() {
  var insideMain = true;

  void myFunction() {
    var insideFunction = true;

    void nestedFunction() {
      var insideNestedFunction = true;

      assert(topLevel);
      assert(insideMain);
      assert(insideFunction);
      assert(insideNestedFunction);
    }
  }
}

注意 nestedFunction() 函数可以访问包括顶层变量在内的所有的变量。

操作符

操作符表

描述操作符
 后缀操作expr++ expr-- () [] . ?.
前缀操作-expr !expr ~expr ++expr --expr
乘除* / % ~/
加减+ -
位移<< >>
按位与&
按位异或
按位或|
类型操作>= > <= < as is is!
相等== !=
逻辑与&&
逻辑或||
是为为空??
三目运算expr1 ? expr2 : expr3
级联..
赋值= *= /= ~/= %= += -= <<= >>= &= ^= |= ??=

优先级顺序 上面左边 优先级高于 右边下面

if(x == 1 && y == 2){
  ...
}

算术操作符

操作符解释
+加号
减号
-expr负号
*乘号
/除号
~/除号,但是返回值为整数
%取模
  print(5/2);
  print(5~/2);
  print(5 % 2);

相等相关的操作符

操作符解释
==相等
!=不等
大于
<小于
>=大于等于
<=小于等于

类型判定操作符

操作符解释
as类型转换
is如果对象是指定的类型返回 True
is!如果对象是指定的类型返回 False
  int a = 123;
  String b = 'ducafecat';
  String c = 'abc';
  print(a as Object);
  print(b is String);
  print(c is! String);

条件表达式

操作符解释
condition ? expr1 : expr2如果 condition 是 true,执行 expr1 (并返回执行的结果); 否则执行 expr2 并返回其结果。
expr1 ?? expr2如果 expr1 是 non-null,返回其值; 否则执行 expr2 并返回其结果。
  bool isFinish = true;
  String txtVal = isFinish ? 'yes' : 'no';

  bool isFinish;
  isFinish = isFinish ?? false;
  or
  isFinish ??= false;

位和移位操作符

操作符解释
&逻辑与
|逻辑或
逻辑异或
~expr取反
<<左移
>>右移

级联操作符

操作符解释
..可以在同一个对象上 连续调用多个函数以及访问成员变量。
  StringBuffer sb = StringBuffer();
  sb
  ..write('hello')
  ..write('word')
  ..write('\n')
  ..writeln('doucafecat');

其他操作符

操作符解释
()使用方法 代表调用一个方法
[]访问 List 访问 list 中特定位置的元素
.访问 Member 访问元素,例如 foo.bar 代表访问 foo 的 bar 成员
?.条件成员访问 和 . 类似,但是左边的操作对象不能为 null,例如 foo?.bar 如果 foo 为 null 则返回 null,否则返回 bar 成员
  String a;
  print(a?.length);

异常

错误的两种类型

Exception 类

Exception class

名称说明
DeferredLoadException延迟加载错误
FormatException格式错误
IntegerDivisionByZeroException整数除零错误
IOExceptionIO 错误
IsolateSpawnException隔离产生错误
TimeoutException超时错误

可以捕获,可以安全处理

Error 类

Error class

名称说明
AbstractClassInstantiationError抽象类实例化错误
ArgumentError参数错误
AssertionError断言错误
AsyncError异步错误
CastErrorCast 错误
ConcurrentModificationError并发修改错误
CyclicInitializationError周期初始错误
FallThroughErrorFall Through 错误
JsonUnsupportedObjectErrorjson 不支持错误
NoSuchMethodError没有这个方法错误
NullThrownErrorNull 错误错误
OutOfMemoryError内存溢出错误
RemoteError远程错误
StackOverflowError堆栈溢出错误
StateError状态错误
UnimplementedError未实现的错误
UnsupportedError不支持错误

一般用在不可恢复,容易崩溃的情况

抛出错误

  // Exception 对象
  throw new FormatException('这是一个格式错误提示');

  // Error 对象
  throw new OutOfMemoryError();

  // 任意对象
  throw '这是一个异常';

捕获错误

  try {
    // throw new FormatException('这是一个格式错误提示');
    throw new OutOfMemoryError();
  } on OutOfMemoryError {
    print('没有内存了');
  } catch (e) {
    print(e);
  }

重新抛出错误

  try {
    throw new OutOfMemoryError();
  } on OutOfMemoryError {
    print('没有内存了');
    rethrow;
  } catch (e) {
    print(e);
  }

Finally 执行

  try {
    throw new OutOfMemoryError();
  } on OutOfMemoryError {
    print('没有内存了');
    rethrow;
  } catch (e) {
    print(e);
  } finally {
    print('end');
  }

自定义异常

class DioError implements Exception {
  DioError(this.message, this.type);

  final String message;
  final String type;

  @override
  String toString() {
    return 'DioError{message: $message, type: $type}';
  }
}

void main(List<String> args) {
  throw DioError("error", "type");
}