Dart语言学习笔记(1)
变量
// 静态变量,类型为 String(隐式声明)
var name = 'Bob';
// 动态变量,类型为 Object 或 dynamic
dynamic name = 'Bob';
// 静态变量,类型为 String(显式声明)
String name = 'Bob';
// 所有类型的缺省值均为 null
int lineCount;
assert(lineCount == null);
// 不变量使用 final 声明
final name = 'Bob'; // Without a type annotation
final String nickname = 'Bobby';
// name = 'Alice'; // Error: a final variable can only be set once.
// 编译期常量使用 const 声明
const bar = 1000000; // Unit of pressure (dynes/cm2)
const double atm = 1.01325 * bar; // Standard atmosphere
// const 还可以用来声明常量对象
var foo = const [];
final bar = const [];
const baz = []; // Equivalent to `const []`
// 用常量对象初始化的变量可以重新赋值
foo = [1, 2, 3]; // Was const []
// baz = [42]; // Error: Constant variables can't be assigned a value.
// 高级语法
// Valid compile-time constants as of Dart 2.5.
const Object i = 3; // Where i is a const Object with an int value...
const list = [i as int]; // Use a typecast.
const map = {if (i is int) i: "int"}; // Use is and collection if.
const set = {if (list is List<int>) ...list}; // ...and a spread.
内置类型
数值类型 num
int 和 double 都是64位,都是 num 的子类型
// int 类型
var x = 1;
var hex = 0xDEADBEEF;
// double 类型
var y = 1.1;
var exponents = 1.42e5;
// int 类型可自动转换为 double 类型
double z = 1; // Equivalent to double z = 1.0.
// 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');
// 位移 与 或
assert((3 << 1) == 6); // 0011 << 1 == 0110
assert((3 >> 1) == 1); // 0011 >> 1 == 0001
assert((3 | 4) == 7); // 0011 | 0100 == 0111
// 编译期常量间的计算
const msPerSecond = 1000;
const secondsUntilRetry = 5;
const msUntilRetry = secondsUntilRetry * msPerSecond;
字符串类型 String
// 字符串类型可以使用单引号或双引号
var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to use the other delimiter.";
// 字符串插值使用 ${expression} 这种形式
var s = 'string interpolation';
assert('Dart has $s, which is very handy.' ==
'Dart has string interpolation, ' +
'which is very handy.');
assert('That deserves all caps. ' +
'${s.toUpperCase()} is very handy!' ==
'That deserves all caps. ' +
'STRING INTERPOLATION is very handy!');
// 字符串比较使用 == 运算符
var s1 = 'String '
'concatenation'
" works even over line breaks.";
assert(s1 ==
'String concatenation works even over '
'line breaks.');
var s2 = 'The + operator ' + 'works, as well.';
assert(s2 == 'The + operator works, as well.');
// 相邻的字符串字面量会自动连接
// 使用 + 运算符连接字符串
var s1 = 'String '
'concatenation'
" works even over line breaks.";
assert(s1 ==
'String concatenation works even over '
'line breaks.');
var s2 = 'The + operator ' + 'works, as well.';
assert(s2 == 'The + operator works, as well.');
// 使用三引号创建多行字符串
var s1 = '''
You can create
multi-line strings like this one.
''';
var s2 = """This is also a
multi-line string.""";
// 原生字符串以 r 打头
var s = r'In a raw string, not even \n gets special treatment.';
// 编译期常量间的计算
// These work in a const string.
const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';
// These do NOT work in a const string.
var aNum = 0;
var aBool = true;
var aString = 'a string';
const aConstList = [1, 2, 3];
//
const validConstString = '$aConstNum $aConstBool $aConstString';
// const invalidConstString = '$aNum $aBool $aString $aConstList';
布尔类型 bool
bool 类型只有 true 和 false 两个。
// Check for an empty string.
var fullName = '';
assert(fullName.isEmpty);
// Check for zero.
var hitPoints = 0;
assert(hitPoints <= 0);
// Check for null.
var unicorn;
assert(unicorn == null);
// Check for NaN.
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);
列表(数组)类型 List
// 类型为 List<int>
var list = [1, 2, 3];
assert(list.length == 3);
assert(list[1] == 2);
list[1] = 1;
assert(list[1] == 1);
// 常量列表
var constantList = const [1, 2, 3];
// constantList[1] = 1; // Uncommenting this causes an error.
// 展开运算符 (...)
var list = [1, 2, 3];
var list2 = [0, ...list];
assert(list2.length == 4);
// 可检测 null 的展开运算符 (...?)
var list;
var list2 = [0, ...?list];
assert(list2.length == 1);
// 在列表内使用 if(collection if)
var nav = [
'Home',
'Furniture',
'Plants',
if (promoActive) 'Outlet'
];
// 在列表内使用 for(collection for)
var listOfInts = [1, 2, 3];
var listOfStrings = [
'#0',
for (var i in listOfInts) '#$i'
];
assert(listOfStrings[1] == '#1');
集类型 Set
var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
// 空集
var names = <String>{};
// Set<String> names = {}; // This works, too.
// var names = {}; // Creates a map, not a set.
// length 方法
var elements = <String>{};
elements.add('fluorine');
elements.addAll(halogens);
assert(elements.length == 5);
// 常量集
final constantSet = const {
'fluorine',
'chlorine',
'bromine',
'iodine',
'astatine',
};
// constantSet.add('helium'); // Uncommenting this causes an error.
// Set 类型也可使用 collection if, collection for,(...), (...?)
映射类型 Map
// 类型为 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',
};
// 添加键值对
var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds'; // Add a key-value pair
// 取出键所对应的值
var gifts = {'first': 'partridge'};
assert(gifts['first'] == 'partridge');
// 键不存在时值为 null
var gifts = {'first': 'partridge'};
assert(gifts['fifth'] == null);
// length 方法
var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds';
assert(gifts.length == 2);
// 常量 Map
final constantMap = const {
2: 'helium',
10: 'neon',
18: 'argon',
};
// constantMap[2] = 'Helium'; // Uncommenting this causes an error.
// Map 类型也可使用 collection if, collection for,(...), (...?)
Unicode 类型 rune
字符串内部采用 UTF-16
\u2665 表示 ♥
\u{1f606} 表示 😆
import 'package:characters/characters.dart';
...
var hi = 'Hi 🇩🇰';
print(hi);
print('The end of the string: ${hi.substring(hi.length - 1)}');
print('The last character: ${hi.characters.last}\n');
// Hi 🇩🇰
// The end of the string: ???
// The last character: 🇩🇰
符号类型 Symbol
#radix
#bar