1.使用相邻字符串或者+号创建字符串
void main() {
//相邻字符串创建方式
var str1 = 'hello'',world'",OK";
print(str1);
//+号连接符创建方式
var str2 = "hello" + 'world';
var str3 = "li" + "huai";
var str4 = '归海' + '一刀';
print("str2=$str2,\nstr3=$str3,\nstr4=$str4");
}
hello,world,OK
str2=helloworld,
str3=lihuai,
str4=归海一刀
2.创建多行字符串—— ''' ... '''
void main() {
var str = '''
锄禾日当午
汗滴禾下土
谁知
盘中
餐
粒粒皆辛苦
''';
print(str);
}
锄禾日当午
汗滴禾下土
谁知
盘中
餐
粒粒皆辛苦
Process finished with exit code 0
3.在字符串前面加上字母小写的r
加r前
var s1 = 'In a raw string, not even \n gets \t special treatment.';
print(s1);
In a raw string, not even
gets special treatment.
字符串中有转义字符可以识别
加r后
var s = r'In a raw string, not even \n gets \t special treatment.';
print(s);
In a raw string, not even \n gets \t special treatment.
加了r,转义符号 \n 换行 \t (按一次tab键的水平制表符)不起作用了
Booleans
bool 类型,只有两个值 true false
结果可以通过布尔表达式计算
void main() {
var fullName = '';
// assert(fullName.isEmpty);
if(fullName.isEmpty){
print("fullName is empty");
}
// Check for zero.
var hitPoints = 0;
// assert(hitPoints <= 0);
if(hitPoints <= 0){
print("hitPoints <= 0");
}
// Check for null.
var unicorn;
// assert(unicorn == null);
if(unicorn == null){
print("uicorn = null");
}
// Check for NaN.
var iMeantToDoThis = 0 / 0;
// assert(iMeantToDoThis.isNaN);
if(iMeantToDoThis.isNaN){
print("0 / 0 不是一个数");
}
}
fullName is empty
hitPoints <= 0
uicorn = null
0 / 0 不是一个数
Process finished with exit code 0
Lists
void main() {
var list = [1,2,3];
var list2 = ["hello","world",1,2,true];
// list2 = list;
bool h = true;
list2[0] = h;
list[0] = 3;
for (var o in list2) {
print(o);
}
}
Maps
map使用key 和 value 进行关联,key和value可以是任意类型的值。
key不能重复,value可以重复。
void main() {
//Map<String,String>
var gifts = {
// Key: Value
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
//Map<int, String>
var nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};
//1.gifts['first'] 中存的是字符串类型,这里我们存入数字类型就会报错
// gifts['first'] = 2;
//2.增加一个新的key-value
gifts['five'] = 'bird';
if(gifts.containsKey('five')){
print(gifts['five']);//bird
}
//3.获取一个不存在的key-value,结果就是null
var x = gifts['seven'];
print("x=$x");//x=null
//4.获取map中有几对 key-vlaue
var y = nobleGases.length;
print("nobleGases's length = $y");//3
//5.使用Map() 代替 new Map() 构造器来创建map
var fans = Map();
fans[1] = '大米';
fans[2] = '小米';
fans[3] = '黑米';
//6.lambda 表达式,向forEach传入一个回调函数
fans.forEach((x,value) => print(fans[x]));
//7.编译时常量的map
final shui = const {
'1':'农夫山泉',
'3':'百岁山',
'5':'怡宝'
};
//Error
// shui = fans;//
//shui['1'] = 'hello';//运行异常
}
bird
x=null
nobleGases's length = 3
大米
小米
黑米
Process finished with exit code 0
网友评论