ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 变量 ``` var name = 'Bob'; //类型推导出 string 类型 String name = 'Bob'; //显示声明 var v1=1; var v2="hello"; var v3=3.3; var v4=true; var v5=[1, 2, 3]; const c1=1; const c2="hello"; const c3=3.3; const c4=true; const c5 = [1, 2, 3]; ``` ### 默认值 未初始化的变量默认值是 null,数字也是null,因为一切皆对象 ``` int lineCount ; assert(lineCount == null); ``` ## Number int * 整数值不大于64位 * 值的范围从 -263 到 263 - 1 float * 64位(双精度)浮点数 方法 * abs(), ceil(), 和 floor() ``` //生成整数 var x = 1; var hex = 0xDEADBEEF; //浮点数 var y = 1.1; var exponents = 1.42e5; //从 Dart 2.1 int 必要时会转为 float double z = 1; // 相当于 double z = 1.0. ``` ### 位运算 ``` assert((3 << 1) == 6); // 0011 << 1 == 0110 assert((3 >> 1) == 1); // 0011 >> 1 == 0001 assert((3 | 4) == 7); // 0011 | 0100 == 0111 ``` ### 字符串,为数字相互转换 ``` // String -> int var one = int.parse('1'); assert(one == 1); // String -> double var onePointOne = double.parse('1.1'); assert(onePointOne == 1.1); // int -> String String oneAsString = 1.toString(); assert(oneAsString == '1'); // double -> String String piAsString = 3.14159.toStringAsFixed(2); assert(piAsString == '3.14'); ``` ## String UTF-16 单元序列。 字符串通过单引号或者双引号创建 ``` var s1 = 'Single quotes work well for string literals.'; var s2 = "Double quotes work just as well."; var s3=""" hello word """; var s4 ="hello "+"word"; var s = r"hello \n word"; // \b 不转义 ``` ### ${expression} 嵌入字符串 ``` var a ="hello"; print('${a} word'); // hello word print("${a} word"); // hello word ``` ## Boolean 不同类型检查 boo 的方法 ``` // 检查空字符串。 var fullName = ''; assert(fullName.isEmpty); // 检查 0 值。 var hitPoints = 0; assert(hitPoints <= 0); // 检查 null 值。 var unicorn; assert(unicorn == null); // 检查 NaN 。 var iMeantToDoThis = 0 / 0; assert(iMeantToDoThis.isNaN); ``` ### 创建空集 ``` var names = <String>{}; // Set<String> names = {}; // 这样也是可以的。 // var names = {}; // 这样会创建一个 Map ,而不是 Set 。 ``` ### 设置 编译时常量 ``` final constantSet = const { 'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine', }; // constantSet.add('helium'); // Uncommenting this causes an error. ``` ## Rune Rune 用来表示字符串中的 UTF-32 编码字符,由于 Dart 字符串是一系列 UTF-16 编码单元, 因此要在字符串中表示32位 Unicode 值需要特殊语法支持 ``` main() { var clapping = '\u{1f44f}'; print(clapping); print(clapping.codeUnits); print(clapping.runes.toList()); Runes input = Runes( '\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}'); print(String.fromCharCodes(input)); //ouput //👏 // [55357, 56399] // [128079] // ♥ 😅 😎 👻 🖖 👍 } ``` ## 枚举类型 ``` enum Color { red, green, blue } //枚举都有 getter 犯法 assert(Color.green.index == 1); //枚举的 values 常量 List<Color> colors = Color.values; assert(colors[2] == Color.blue); var aColor = Color.blue; switch (aColor) { case Color.red: print('Red as roses!'); break; case Color.green: print('Green as grass!'); break; default: // 没有这个,会看到一个警告。 print(aColor); // 'Color.blue' } ``` ## typedef 声明一种类型 ``` typedef int Compare(int a, int b); int sort(int a, int b) => a - b; main() { print(sort is Compare); //true } ```