Dart-变量

dart基础类型包括三大类型

  • Number (数字类型)
    • int
    • double
  • Boolean
  • String
//基础变量声明
int age = 18;
double height = 175.2;
bool done = false;
String name = "高富帅";

//推导类型
var oneInt=1;
assert(oneInt.runtimeType is int);

var oneString="1";
assert(oneString.runtimeType is String);

var oneBool=false;
assert(oneBool.runtimeType is bool);

final

final 只允许被赋值一次,赋值以后就不能在被set
只能get

const

定义常量使用,定义以后就不能再被改变

const String  menu="MENU";

常用方式

 //String转int
 int one=int.parse("1");
 assert(one==1);

 //String转double
 double two=double.parse("1.1");
 assert(two==1.1);

 //double转String
 String three=1.toString();
 assert(three=="1");

 //double转String
 String four=1.2.toString();
 assert(four=="1.2");

 //取小数点后2位数(四舍五入)
 String five=12.185421.toStringAsFixed(2);
 assert(five=="12.19");
 
 //小写转大写
 var str = ' foo';
 var str2 = str.toUpperCase();

注意

1,转义字符

当String中有转义字符时,想要在输出的时候保持转义格式,可以在字符串之前加一个 " r "

String value = r"this is \n string \t value";

2,?? 与 ??=

  • A ?? B

如果 A 非null 就取A,否则就取 B

String key;
String value=key??"test";
assert(value=="test");
  • A ??= B

如果 A 为null 就把B 赋值给A

String key;
String value=key??="test";
assert(key=="test");

你可能感兴趣的:(Dart-变量)