Skip to content

运算符

算术运算符

加、减、乘、除、取余、取整

dart
void main() {
  int a = 13;
  int b = 5;
  print(a + b);
  print(a - b);
  print(a * b);
  print(a / b);
  print(a % b);
  print(a ~/ b);
}

image-20240711123350193

关系运算符

dart
void main() {
  int a = 13;
  int b = 5;
  print(a == b);
  print(a != b);
  print(a > b);
  print(a < b);
  print(a >= b);
  print(a <= b);
}

逻辑运算符

取反!、并集&、或者||

赋值运算符

基础赋值运算符= 、??=

dart
void main() {
  int b = 10;
  b ??= 23; # b等于空就赋值23
  print(b);
}

复合赋值运算符

+=、-=、*=、/=、%=、~/=

条件运算符

if else、switch case、三目运算符xx?xx:xx、同js的逻辑写法一样

a??b如果a为空就取b的值

类型转换

Number与String类型之间的转换

Number类型转换成String类型tostring()

String类型转换成Number类型parse()

转数字

dart
void main() {
  String str1 = '123';
  var num1 = int.parse(str1);
  print(num1);
  print(num1 is int);
    
  String str2 = '123.123';
  var num2 = double.parse(str2);
  print(num2);
  print(num2 is double);
}
# 建议用double来转换

image-20240711125313014

报错处理

dart
void main() {
  String str = '';
  try {
    var b = double.parse(str);
    print(b);
  } catch (e) {
    print(0);
  }
}

转字符串

dart
void main() {
  var num = 123;
  try {
    var b = num.toString();
    print(b);
  } catch (e) {
    print(0);
  }
}

判断字符串是否为空

dart
void main() {
  var str = '123';
  if (str.isEmpty) {
    print('str为空');
  } else {
    print('str不为空');
  }
}