/**
* 1.hello word
*/
main(List<String> args) {
print("hello dart");
//2.定义变量
String name = "小明";
int age = 18;
double height = 1.88;
print('name = ${name} and age = ${age} and height = ${height}');
//3.类型推导
//3.1 var的使用
var myName = "小红";
//获取当前变量的类型
print(myName.runtimeType);
//3.2 dynamic的使用
//如果想改变变量的类,可以使用dynamic
dynamic youName = "小王";
print(youName.runtimeType);
youName = 12;
print(youName.runtimeType);
//3.3 final&const的使用
//他们俩都表示常量,
//区别在于const在编译期间就确定了值
//而finale可以在运行时确定值
//所以 const name = getName(); // 错误的做法, 因为要执行函数才能获取到值
// final name = getName(); // 正确的做法
final finalName = "cody";
const constName = "youdy";
print('finalname = ${finalName} and constName = ${constName}');
//4.数据类型
//4.1数字类型
//整型int 浮点型double
//Dart中的int和double可表示的范围并不是固定的,它取决于运行Dart的平台。
int myInt = 12;
double myDouble = 12.22;
//类型转换
String myStr1 = myInt.toString();
String myStr2 = myDouble.toString();
int a = int.parse(myStr1);
double b = double.parse(myStr2);
print(
"myInt = ${myInt} and myDouble = ${myDouble} and myStr1 = ${myStr1} and myStr2 = ${myStr2} and a = ${a} and b = ${b}");
//4.2布尔类型
bool flag = false;
var isFlag = true;
print('flag = ${flag} and isFlag = ${isFlag}');
if (isFlag) {
print('这是真的');
}
//4.3字符串类型
String str = "你好";
var str2 = "世界";
print('str = ${str} and str2 = ${str2}');
// 表示多行字符串的方式
//直接表示多行
var message1 = '''
哈哈哈
呵呵呵
嘿嘿嘿''';
print(message1);
//4.4集合类型
//对于集合类型,Dart则内置了最常用的三种:List / Set / Map。
//4.4.1 List
//使用类型推导
var letters = ['a','b','c'];
print('${letters}');
//使用明确类型
List<int> numbers = [1,2,3];
print('${numbers}');
//4.4.2使用Set
//使用set也就是把[] 改成{ }
var sets1 = {"a","b","c"};
Set<int> sets2 = {1,2,3};
print('sets1 = ${sets1} and sets2 = ${sets2}');
//4.4.3 使用map
var map1 = {"name":"小红","age":12};
Map<String,String> map2 = {"name":"小明","sex":"男"};
print('map1 = ${map1} and map2 = ${map2}');
//4.4.4集合的操作
//1.获取集合的长度
print(numbers.length);
print(sets2.length);
print(map2.length);
//2.添加,删除,包含元素
numbers.add(2);
sets2.add(3);
numbers.remove(1);
sets2.remove(2);
numbers.contains(2);
sets2.contains(3);
//3.map的操作
//根据key取值
print(map2["name"]);
//获取所有的entries
print("${map2.entries}");
//获取所有的keys
print("${map2.keys}");
//获取所有的value
print("${map2.values}");
//判断是否包含某个key或者value
print('${map2.containsKey("name")}');
print('${map2.containsValue("男")}');
//根据key删除元素
map2.remove("name");
print('${map2}');
}
网友评论