String
ini
void main(List<String> args) {
String hi = "Hello";
var welcome = "欢迎";
// 模板字符串,可以用$变量名称或者${变量名}
String hi_xiaoming = '$hi xiaoming';
var welcome_xiaoming = "${welcome} 小明";
print(hi_xiaoming);
print(welcome_xiaoming);
}
数字
int和double类型不可以直接赋值。
int和double可以直接赋值给num类型。
-17 % 5 = 3 。是因为余数和除数4保持符合相同。-4 * 5 + 3 = 17
scss
// =====================================================
// Dart 数字类型(num / int / double)完整练习
// =====================================================
void main() {
print('【1. 基本类型声明】');
sectionBasicTypes();
print('\n【2. 数值字面量写法】');
sectionLiterals();
print('\n【3. 运算符:~/ 整除、% 取模、/ 除法】');
sectionOperators();
print('\n【4. 位运算】');
sectionBitwise();
print('\n【5. 常用数学方法】');
sectionMathMethods();
print('\n【6. 特殊值与检查】');
sectionSpecialValues();
print('\n【7. 字符串与数字互转】');
sectionStringConversion();
print('\n【8. 类型检查与 is 关键字】');
sectionTypeCheck();
print('\n【9. 可空类型】');
sectionNullable();
print('\n【10. 常量与不可变数字】');
sectionConstFinal();
}
// -------------------------------------------------------
// 1. 基本类型声明
// -------------------------------------------------------
void sectionBasicTypes() {
int a = 20;
num b = 20; // num 是 int 和 double 的父类型
b = 30.12; // num 可以同时存储 int 和 double
double c = 20.1;
c = 100; // double 可以接收整数字面量(自动转为 100.0)
print('int a = $a, num b = $b, double c = $c');
a = c.toInt(); // double → int
c = a.toDouble(); // int → double
print('转换后:a = $a, b = $b, c = $c');
}
// -------------------------------------------------------
// 2. 数值字面量写法
// -------------------------------------------------------
void sectionLiterals() {
// 十进制
int dec = 42;
print('十进制: $dec');
// 十六进制 (0x 前缀)
int hex = 0xFF;
print('十六进制 0xFF: $hex');
// 二进制: 使用 int.parse 配合 radix 参数
int bin = int.parse('1010', radix: 2);
print('二进制 1010 (radix 2): $bin');
// 八进制没有直接写法,用 hex 或十进制
// 科学计数法
double sci = 1.5e10;
print('科学计数法 1.5e10: $sci');
// 数字分隔符(Dart 2.3+),仅用于可读性
int largeNumber = 1_000_000_000;
print('带分隔符 1_000_000_000: $largeNumber');
double piLike = 3.141_592_653_589_793;
print('带分隔符 3.141_592_653_589_793: $piLike');
}
// -------------------------------------------------------
// 3. 运算符
// -------------------------------------------------------
void sectionOperators() {
int x = 17;
int y = 5;
print('x = $x, y = $y');
print('x + y = ${x + y}'); // 加法
print('x - y = ${x - y}'); // 减法
print('x * y = ${x * y}'); // 乘法
print('x / y = ${x / y}'); // 除法(结果为 double)
print('x ~/ y = ${x ~/ y}'); // 整除(截断,结果为 int)
print('x % y = ${x % y}'); // 取模(余数)
print('x - y * (x ~/ y) = ${x - y * (x ~/ y)}'); // 验证: 被除数 - 除数 × 商 = 余数
// 负数整除
print('(-17) ~/ 5 = ${(-17) ~/ 5}'); // 向零截断: -3
print('(-17) % 5 = ${(-17) % 5}'); // Dart 保证余数与除数同号: 3
}
// -------------------------------------------------------
// 4. 位运算
// -------------------------------------------------------
void sectionBitwise() {
int a = 5; // 0101
int b = 3; // 0011
print('a = $a (${a.toRadixString(2).padLeft(4, '0')})');
print('b = $b (${b.toRadixString(2).padLeft(4, '0')})');
print('a & b = ${a & b} (${(a & b).toRadixString(2).padLeft(4, '0')}) 按位与');
print('a | b = ${a | b} (${(a | b).toRadixString(2).padLeft(4, '0')}) 按位或');
print('a ^ b = ${a ^ b} (${(a ^ b).toRadixString(2).padLeft(4, '0')}) 按位异或');
print('~a = ${~a} 按位取反');
print('a << 1 = ${a << 1} 左移1位 (×2)');
print('a >> 1 = ${a >> 1} 右移1位 (/2)');
// 使用 toRadixString 查看不同进制
int n = 255;
print('255 的二进制: ${n.toRadixString(2)}');
print('255 的十六进制: ${n.toRadixString(16)}');
}
// -------------------------------------------------------
// 5. 常用数学方法
// -------------------------------------------------------
void sectionMathMethods() {
double val = 3.7;
double negVal = -3.7;
print('原始值: $val, 负值: $negVal');
print('abs($negVal) = ${negVal.abs()}'); // 绝对值: 3.7
print('ceil($val) = ${val.ceil()}'); // 向上取整: 4
print('floor($val) = ${val.floor()}'); // 向下取整: 3
print('round($val) = ${val.round()}'); // 四舍五入: 4
print('truncate($val) = ${val.truncate()}'); // 截断小数: 3
print('remainder(2) = ${val.remainder(2)}'); // 浮点余数
// clamp: 限制在范围内
print('clamp(1.0, 2.5) on $val = ${val.clamp(1.0, 2.5)}'); // 2.5
// gcd: 最大公约数 (int 类型)
int g = 24.gcd(36);
print('24.gcd(36) = $g'); // 12
// sign: 符号
print('sign of 5 = ${5.sign}'); // 1
print('sign of -5 = ${(-5).sign}'); // -1
print('sign of 0 = ${0.sign}'); // 0
}
// -------------------------------------------------------
// 6. 特殊值与检查
// -------------------------------------------------------
void sectionSpecialValues() {
double nan = double.nan;
double inf = double.infinity;
double negInf = double.negativeInfinity;
print('NaN: $nan');
print('Infinity: $inf');
print('Negative Infinity: $negInf');
print('NaN.isNaN: ${nan.isNaN}');
print('NaN.isFinite: ${nan.isFinite}');
print('NaN.isInfinite: ${nan.isInfinite}');
double normal = 3.14;
print('$normal.isFinite: ${normal.isFinite}');
print('$normal.isNegative: ${normal.isNegative}');
print('$normal.isInfinite: ${normal.isInfinite}');
// 注意:NaN 与任何值都不相等,包括自身
print('NaN == NaN: ${nan == nan}'); // false!要用 isNaN 检查
}
// -------------------------------------------------------
// 7. 字符串与数字互转
// -------------------------------------------------------
void sectionStringConversion() {
// 数字 → 字符串
int i = 42;
double d = 3.14159;
print('int.toString(): ${i.toString()}');
print('double.toString(): ${d.toString()}');
print('toStringAsFixed(2): ${d.toStringAsFixed(2)}'); // 保留2位小数: 3.14
print('toStringAsPrecision(4): ${d.toStringAsPrecision(4)}'); // 4位有效数字: 3.142
print('toStringAsExponential(2): ${d.toStringAsExponential(2)}'); // 科学计数法: 3.14e+00
// 字符串 → 数字
String s1 = '123';
String s2 = '3.14';
print('int.parse("$s1"): ${int.parse(s1)}');
print('double.parse("$s2"): ${double.parse(s2)}');
// tryParse: 解析失败返回 null,不会抛异常
String invalid = 'abc';
int? result = int.tryParse(invalid);
print('int.tryParse("$invalid"): $result'); // null
// 进制解析
print('int.parse("ff", radix: 16): ${int.parse("ff", radix: 16)}'); // 255
print('int.parse("1010", radix: 2): ${int.parse("1010", radix: 2)}'); // 10
}
// -------------------------------------------------------
// 8. 类型检查与 is 关键字
// -------------------------------------------------------
void sectionTypeCheck() {
num value = 42;
print('value = $value');
print('value is int: ${value is int}');
print('value is double: ${value is double}');
print('value is num: ${value is num}');
value = 3.14;
print('value = $value');
print('value is int: ${value is int}');
print('value is double: ${value is double}');
// as 类型转换(用于确定类型的场景)
if (value is int) {
int iv = value as int;
print('转换为 int: $iv');
} else {
print('不是 int 类型');
}
}
// -------------------------------------------------------
// 9. 可空类型
// -------------------------------------------------------
void sectionNullable() {
int? nullableInt; // 默认值为 null
double? nullableDouble;
num? nullableNum;
print('int? 默认值: $nullableInt');
print('double? 默认值: $nullableDouble');
print('num? 默认值: $nullableNum');
nullableInt = 10;
print('赋值后: $nullableInt');
// 非空断言 ! (如果为 null 会抛异常)
int nonNull = nullableInt!;
print('非空断言: $nonNull');
// 安全调用 ?. 和 ?? 运算符
int? maybeNull;
int fallback = maybeNull ?? 0; // 如果为 null 则使用 0
print('?? 运算符: $fallback');
// 闭区间
int x = nullableInt ??= 100; // 如果为 null 则赋值 100
print('??= 赋值: $x');
}
// -------------------------------------------------------
// 10. 常量与不可变数字
// -------------------------------------------------------
void sectionConstFinal() {
// const: 编译期常量
const int speedOfLight = 299792458;
const double pi = 3.141592653589793;
print('光速常量: $speedOfLight');
print('π 常量: $pi');
// final: 运行期不可变
final int now = DateTime.now().millisecondsSinceEpoch;
print('时间戳 (final): $now');
// const 集合
const List<int> primeNumbers = [2, 3, 5, 7, 11, 13];
print('质数常量列表: $primeNumbers');
}
bool类型
| # | 主题 | 关键内容 |
|---|---|---|
| 1 | 基本声明 | true/false,表达式赋值,Dart 无 truthy/falsy 概念 |
| 2 | 逻辑运算符 | ! 非、&& 与、` |
| 3 | 关系运算符 | > < >= <= == !=,字符串比较 |
| 4 | 短路求值 | && 左边为 false 不执行右侧,` |
| 5 | 类型转换 | toString()、字符串转 bool(手动)、as bool 断言 |
| 6 | 可空 bool | bool?、! 非空断言、?? 默认值、??= 赋值 |
| 7 | 常见场景 | 三元运算符、if/while 判断、assert 断言、List<bool> |
💡 重点提醒
- Dart 是强类型 的布尔系统,
if(1)、if('')、if(null)都会编译报错,条件必须是bool类型 - Dart 没有
bool.parse(),字符串转 bool 需手动:s.toLowerCase() == 'true' assert()只在 debug 模式生效,release 模式会被忽略
dart
// =====================================================
// Dart 布尔类型(bool)完整练习
// =====================================================
void main() {
print('【1. 基本声明】');
sectionBasic();
print('\n【2. 逻辑运算符】');
sectionLogical();
print('\n【3. 关系运算符(产生 bool)】');
sectionRelational();
print('\n【4. 短路求值】');
sectionShortCircuit();
print('\n【5. 类型转换与断言】');
sectionConversion();
print('\n【6. 可空 bool 与默认值】');
sectionNullable();
print('\n【7. 常见使用场景】');
sectionUsage();
}
// -------------------------------------------------------
// 1. 基本声明
// -------------------------------------------------------
void sectionBasic() {
bool finish = true;
bool isMen = false;
print('finish = $finish');
print('isMen = $isMen');
// 通过表达式赋值
bool isAdult = 20 >= 18;
print('20 >= 18 => $isAdult');
// bool 类型只有两个值:true / false
// 注意:Dart 中没有 "truthy" / "falsy" 概念
// 例如 if (1) 或 if ('') 都会报错,必须是 bool 类型
}
// -------------------------------------------------------
// 2. 逻辑运算符
// -------------------------------------------------------
void sectionLogical() {
bool a = true;
bool b = false;
print('a = $a, b = $b');
print('!a (非) = ${!a}'); // 取反
print('a && b (与) = ${a && b}'); // 两者都为 true 才为 true
print('a || b (或) = ${a || b}'); // 两者有一个为 true 就为 true
// 组合运算
bool result = (a || b) && !b;
print('(a || b) && !b = $result');
}
// -------------------------------------------------------
// 3. 关系运算符(产生 bool)
// -------------------------------------------------------
void sectionRelational() {
int x = 10;
int y = 20;
print('x = $x, y = $y');
print('x > y: ${x > y}');
print('x < y: ${x < y}');
print('x >= y: ${x >= y}');
print('x <= y: ${x <= y}');
print('x == y: ${x == y}');
print('x != y: ${x != y}');
// 字符串也可以比较
print('"abc" == "abc": ${"abc" == "abc"}');
print('"abc" != "abd": ${"abc" != "abd"}');
}
// -------------------------------------------------------
// 4. 短路求值
// -------------------------------------------------------
void sectionShortCircuit() {
// && 短路:左边为 false 时,右边不执行
bool debug = false;
bool r1 = debug && printLog('这行不会执行');
print('debug && printLog() => $r1');
debug = true;
bool r2 = debug && printLog('这行会执行');
print('debug && printLog() => $r2');
// || 短路:左边为 true 时,右边不执行
bool production = true;
bool r3 = production || printLog('这行不会执行(|| 短路)');
print('production || printLog() => $r3');
}
// 辅助函数:打印日志并返回 true
bool printLog(String msg) {
print(' [LOG] $msg');
return true;
}
// -------------------------------------------------------
// 5. 类型转换与断言
// -------------------------------------------------------
void sectionConversion() {
// bool → 字符串
bool ok = true;
print('bool.toString(): ${ok.toString()}');
// 字符串 → bool(Dart 没有内置的 bool.parse,需要手动处理)
String s = 'true';
bool parsed = s.toLowerCase() == 'true';
print('字符串 "true" → bool: $parsed');
String s2 = 'false';
bool parsed2 = s2.toLowerCase() == 'true';
print('字符串 "false" → bool: $parsed2');
// 整数 → bool(0 为 false,非 0 为 true,需手动转换)
int code = 0;
bool isSuccess = code != 0;
print('code = $code → bool: $isSuccess');
// as 断言(用于 Object? 转 bool)
Object obj = true;
bool fromObj = obj as bool;
print('Object as bool: $fromObj');
}
// -------------------------------------------------------
// 6. 可空 bool 与默认值
// -------------------------------------------------------
void sectionNullable() {
bool? nullableBool; // 默认 null
print('bool? 默认值: $nullableBool');
nullableBool = true;
print('赋值后: $nullableBool');
// 非空断言 !
bool nonNull = nullableBool!;
print('非空断言: $nonNull');
// ?? 默认值
bool? maybeNull;
bool value = maybeNull ?? false;
print('?? 默认值: $value');
// ??= 赋默认值
bool? flag;
flag ??= false;
print('??= 后: $flag');
// 显式检查 null 而非 bool 值
bool? settings = null;
if (settings == null) {
print('settings 为 null');
} else if (settings) {
print('settings 为 true');
} else {
print('settings 为 false');
}
}
// -------------------------------------------------------
// 7. 常见使用场景
// -------------------------------------------------------
void sectionUsage() {
// 条件表达式
bool isLogin = true;
String message = isLogin ? '欢迎回来' : '请先登录';
print('三元运算符: $message');
// if 判断
bool hasPermission = false;
if (hasPermission) {
print('允许访问');
} else {
print('拒绝访问');
}
// while 循环
int count = 0;
bool running = true;
while (running) {
count++;
if (count >= 3) running = false;
}
print('while 循环结束, count = $count');
// assert 断言(只在 debug 模式生效)
int age = 18;
assert(age >= 18, '年龄必须大于等于 18');
print('assert 通过: age = $age');
// 集合中的 bool
List<bool> flags = [true, false, true, false];
print('bool 列表: $flags');
print('包含 true: ${flags.contains(true)}');
print('true 的数量: ${flags.where((f) => f).length}');
}
List
toolName: view_files
status: success
filePath: /Users/long/Desktop/dart/test.dart
当前文件已有基础的 List 声明和增删操作,我来扩展完整的 List 知识点。
toolName: Write
status: success
filePath: /Users/long/Desktop/dart/test.dart
changes: undefined
toolName: run_command
status: success
command: cd /Users/long/Desktop/dart && dart run test.dart undefined
Map<String, int> 不能存放 String 类型的 name 值,需要修复类型声明:
toolName: edit_file_search_replace
status: success
filePath: /Users/long/Desktop/dart/test.dart
changes: undefined
toolName: run_command
status: success
command: cd /Users/long/Desktop/dart && dart run test.dart undefined
全部 9 个模块运行成功,输出正确。已补充 List 的完整知识点:
📋 涵盖的知识点
| # | 主题 | 关键内容 |
|---|---|---|
| 1 | 基本声明 | 动态 List vs 泛型 List<T>,var 推断,空 List |
| 2 | 创建方式 | generate、filled、of、from、unmodifiable、expand 展开嵌套 |
| 3 | 添加操作 | add、addAll、insert、insertAll、.. 级联操作符 |
| 4 | 删除操作 | remove、removeAt、removeLast、removeRange、removeWhere、retainWhere、clear |
| 5 | 访问与遍历 | 索引访问、first/last、for、for-in、forEach、asMap |
| 6 | 查询操作 | contains、indexOf、lastIndexOf、indexWhere、firstWhere、any、every、isEmpty/isNotEmpty |
| 7 | 排序与转换 | sort 自定义比较、reversed、shuffle、sublist、setRange、fillRange |
| 8 | 高级操作 | where、map、expand、reduce、fold、join、toSet 去重、链式调用 |
| 9 | 特殊 List | 可空 List<int>?、不可变 unmodifiable、固定长度 growable:false、int? 可空元素 |
💡 重点提醒
- 泛型优先 :
List<int>比List更安全,编译器会帮你检查类型 - 链式调用 :
..级联操作符让连续操作更简洁 reducevsfold:reduce至少要有一个元素,fold可以有空列表(有初始值)whereType:快速过滤特定类型元素,如list.whereType<int>().toList()
dart
// =====================================================
// Dart List 完整知识点练习
// =====================================================
void main() {
print('【1. 基本声明:动态类型 vs 泛型】');
sectionBasic();
print('\n【2. 创建方式】');
sectionCreate();
print('\n【3. 添加操作】');
sectionAdd();
print('\n【4. 删除操作】');
sectionRemove();
print('\n【5. 访问与遍历】');
sectionAccess();
print('\n【6. 查询操作】');
sectionQuery();
print('\n【7. 排序与转换】');
sectionSort();
print('\n【8. 高级操作:where / map / expand / reduce / fold】');
sectionTransform();
print('\n【9. 可空、不可变与固定长度】');
sectionSpecial();
}
// -------------------------------------------------------
// 1. 基本声明
// -------------------------------------------------------
void sectionBasic() {
// 动态类型 List(不指定泛型,可存放任意类型)
List l1 = ['a', 12, true];
print('动态类型 List: $l1');
// 泛型 List(强类型,只能存放指定类型)
List<String> l2 = ['a', 'b', 'c'];
print('泛型 List<String>: $l2');
List<int> l3 = [1, 2, 3];
print('泛型 List<int>: $l3');
// 类型推断
var l4 = <double>[1.0, 2.5, 3.14];
print('var 推断 List<double>: $l4');
// 空 List
List<String> empty = [];
print('空 List: $empty, length = ${empty.length}');
}
// -------------------------------------------------------
// 2. 创建方式
// -------------------------------------------------------
void sectionCreate() {
// List.generate: 按规则生成
List<int> squares = List.generate(5, (i) => i * i);
print('generate 生成平方数: $squares');
// List.filled: 填充固定值
List<String> filled = List.filled(3, 'hello');
print('filled 填充: $filled');
// List.of: 从已有集合创建(类型转换)
List<int> fromList = List.of([1, 2, 3]);
print('List.of: $fromList');
// List.unmodifiable: 创建不可变列表
List<int> unmod = List.unmodifiable([1, 2, 3]);
print('unmodifiable: $unmod');
// unmod.add(42); // 运行时不可变,会抛异常
// List.from: 从已有列表创建(可指定 growable)
List<int> from = List.from([10, 20, 30]);
print('List.from: $from');
// List.cast: 类型转换(运行时检查)
List mixed = [1, 2, 3];
List<int> casted = List<int>.from(mixed); // 推荐用 .from
print('类型转换: $casted');
// expand: 展开嵌套结构
List nested = [1, [2, 3], [4, [5, 6]]];
List flat = nested.expand((e) => e is List ? e : [e]).toList();
print('展开嵌套: $flat');
}
// -------------------------------------------------------
// 3. 添加操作
// -------------------------------------------------------
void sectionAdd() {
List<int> list = [1, 2, 3];
print('初始: $list');
// add: 末尾添加单个元素
list.add(4);
print('add(4): $list');
// addAll: 末尾批量添加
list.addAll([5, 6]);
print('addAll([5,6]): $list');
// insert: 在指定位置插入
list.insert(0, 0);
print('insert(0, 0): $list');
// insertAll: 在指定位置批量插入
list.insertAll(2, [100, 200]);
print('insertAll(2, [100,200]): $list');
// 级联操作符 .. 链式调用
List<int> chained = []
..add(1)
..add(2)
..addAll([3, 4])
..insert(0, 0);
print('级联操作: $chained');
}
// -------------------------------------------------------
// 4. 删除操作
// -------------------------------------------------------
void sectionRemove() {
List<String> list = ['a', 'b', 'c', 'd', 'e'];
print('初始: $list');
// remove: 删除第一个匹配的元素
list.remove('b');
print("remove('b'): $list");
// removeAt: 按索引删除
list.removeAt(1);
print('removeAt(1): $list');
// removeLast: 删除最后一个
list.removeLast();
print('removeLast(): $list');
// removeRange: 删除指定范围 [start, end)
List<int> list2 = [10, 20, 30, 40, 50];
list2.removeRange(1, 3);
print('removeRange(1,3): $list2');
// removeWhere: 按条件删除
List<int> nums = [1, 2, 3, 4, 5, 6];
nums.removeWhere((x) => x % 2 == 0);
print('removeWhere(偶数): $nums');
// retainWhere: 保留满足条件的(与 removeWhere 相反)
List<int> nums2 = [1, 2, 3, 4, 5, 6];
nums2.retainWhere((x) => x % 2 == 0);
print('retainWhere(偶数): $nums2');
// clear: 清空所有元素
list.clear();
print('clear(): $list');
}
// -------------------------------------------------------
// 5. 访问与遍历
// -------------------------------------------------------
void sectionAccess() {
List<String> fruits = ['apple', 'banana', 'cherry', 'date'];
print('水果列表: $fruits');
// 索引访问
print('fruits[0]: ${fruits[0]}');
print('fruits[1]: ${fruits[1]}');
// 安全访问:超出范围不会报错
// 注意:Dart 没有内置 getOrElse,需要手动处理
int index = 10;
if (index < fruits.length) {
print('fruits[$index]: ${fruits[index]}');
} else {
print('索引 $index 越界');
}
// first / last / single
print('first: ${fruits.first}');
print('last: ${fruits.last}');
// single: 只有一个元素时使用,否则抛异常
// for 循环
print('for 循环:');
for (int i = 0; i < fruits.length; i++) {
print(' [$i] ${fruits[i]}');
}
// for-in 循环
print('for-in 循环:');
for (String fruit in fruits) {
print(' $fruit');
}
// forEach: 使用回调
print('forEach:');
fruits.forEach((fruit) => print(' $fruit'));
// asMap: 转为 Map(索引 → 元素)
Map<int, String> mapped = fruits.asMap();
print('asMap: $mapped');
}
// -------------------------------------------------------
// 6. 查询操作
// -------------------------------------------------------
void sectionQuery() {
List<int> nums = [10, 20, 30, 40, 50, 30];
print('列表: $nums');
// contains: 是否包含某元素
print('contains(30): ${nums.contains(30)}');
print('contains(99): ${nums.contains(99)}');
// indexOf: 查找第一个匹配的索引(找不到返回 -1)
print('indexOf(30): ${nums.indexOf(30)}');
// lastIndexOf: 查找最后一个匹配的索引
print('lastIndexOf(30): ${nums.lastIndexOf(30)}');
// indexWhere: 按条件查找索引
print('indexWhere(>25): ${nums.indexWhere((x) => x > 25)}');
// lastIndexWhere: 按条件从后往前查找
print('lastIndexWhere(>25): ${nums.lastIndexWhere((x) => x > 25)}');
// firstWhere / lastWhere: 按条件查找元素
print('firstWhere(>25): ${nums.firstWhere((x) => x > 25)}');
print('lastWhere(>25): ${nums.lastWhere((x) => x > 25)}');
// any: 至少一个满足条件
print('any(>40): ${nums.any((x) => x > 40)}');
// every: 全部满足条件
print('every(>0): ${nums.every((x) => x > 0)}');
// isEmpty / isNotEmpty
print('isEmpty: ${nums.isEmpty}');
print('isNotEmpty: ${nums.isNotEmpty}');
// length
print('length: ${nums.length}');
}
// -------------------------------------------------------
// 7. 排序与转换
// -------------------------------------------------------
void sectionSort() {
List<int> nums = [5, 2, 8, 1, 9, 3];
print('原始: $nums');
// sort: 原地排序(默认升序)
nums.sort();
print('sort() 升序: $nums');
// 自定义排序
List<int> nums2 = [5, 2, 8, 1, 9, 3];
nums2.sort((a, b) => b.compareTo(a)); // 降序
print('sort 降序: $nums2');
// 字符串排序
List<String> words = ['banana', 'apple', 'cherry'];
words.sort();
print('字符串排序: $words');
// 多条件排序
List<Map<String, dynamic>> people = [
{'name': '张三', 'age': 25},
{'name': '李四', 'age': 20},
{'name': '王五', 'age': 30},
];
// 先按年龄排序
people.sort((a, b) => (a['age'] as int).compareTo(b['age'] as int));
print('按年龄排序: $people');
// reversed: 反转(返回新的 Iterable)
List<int> reversedList = nums.reversed.toList();
print('reversed: $reversedList');
// shuffle: 随机打乱
List<int> shuffled = List.from(nums)..shuffle();
print('shuffle 打乱: $shuffled');
// sublist: 截取子列表 [start, end)
List<int> sub = nums.sublist(1, 4);
print('sublist(1,4): $sub');
// getRange: 取范围(返回 Iterable)
List<int> range = nums.getRange(1, 4).toList();
print('getRange(1,4): $range');
// setRange: 修改指定范围
List<int> list3 = [1, 2, 3, 4, 5];
list3.setRange(1, 3, [10, 20]);
print('setRange(1,3,[10,20]): $list3');
// fillRange: 填充指定范围
List<int> list4 = [1, 2, 3, 4, 5];
list4.fillRange(1, 4, 0);
print('fillRange(1,4,0): $list4');
// asMap: 转为 Map
Map<int, int> mapFromList = nums.asMap();
print('asMap: $mapFromList');
}
// -------------------------------------------------------
// 8. 高级操作
// -------------------------------------------------------
void sectionTransform() {
List<int> nums = [1, 2, 3, 4, 5];
print('原始: $nums');
// where: 过滤
List<int> even = nums.where((x) => x % 2 == 0).toList();
print('where 过滤偶数: $even');
// map: 转换每个元素
List<String> mapped = nums.map((x) => 'item_$x').toList();
print('map 转换: $mapped');
// expand: 一对多展开
List<List<int>> nested = [[1, 2], [3, 4], [5]];
List<int> flat = nested.expand((x) => x).toList();
print('expand 展开: $flat');
// reduce: 聚合为单个值(至少一个元素)
int sum = nums.reduce((a, b) => a + b);
print('reduce 求和: $sum');
// fold: 带初始值的聚合(类似 reduce,但有初始值)
int sumWithInit = nums.fold(10, (a, b) => a + b);
print('fold 从10求和: $sumWithInit');
// join: 拼接为字符串
String joined = nums.join('-');
print('join("-"): $joined');
// toSet: 转为 Set(去重)
List<int> dup = [1, 2, 2, 3, 3, 3];
Set<int> unique = dup.toSet();
print('去重 toSet: $unique');
// 链式调用
List<int> result = nums
.where((x) => x > 1)
.map((x) => x * 10)
.toList();
print('链式 where+map: $result');
}
// -------------------------------------------------------
// 9. 可空、不可变与固定长度
// -------------------------------------------------------
void sectionSpecial() {
// 可空 List
List<int>? nullableList;
print('List<int>? 默认值: $nullableList');
// 安全访问
nullableList = [1, 2, 3];
int? first = nullableList?.first;
print('?.first 安全访问: $first');
// ?? 默认值
int count = nullableList?.length ?? 0;
print('?? 默认 length: $count');
// 不可变列表
List<int> fixed = List.unmodifiable([1, 2, 3]);
print('不可变列表: $fixed');
// fixed.add(42); // 运行时会抛 UnsupportedError
// 固定长度列表(growable: false)
List<int> fixedLen = List.filled(3, 0, growable: false);
fixedLen[0] = 10;
fixedLen[1] = 20;
print('固定长度: $fixedLen');
// fixedLen.add(30); // 运行时会抛 UnsupportedError
// 可空元素的 List
List<int?> nullableElements = [1, null, 3, null];
print('含 null 元素: $nullableElements');
print('过滤 null: ${nullableElements.whereType<int>().toList()}');
// List 类型检查
List mixed = [1, 'a', 2.5];
print('List 类型: ${mixed.runtimeType}');
print('元素类型: ${mixed.first.runtimeType}');
}
map
toolName: view_files
status: success
filePath: /Users/long/Desktop/dart/test.dart
toolName: todo_write
status: success
Todos updated: 3 items
现在我来补充 Dart Map 的全面知识点,包括泛型、工厂构造、查询、变换、遍历等高级用法
toolName: edit_file_search_replace
status: success
filePath: /Users/long/Desktop/dart/test.dart
changes: undefined
发现第 177 行有个 bug,修复一下
toolName: edit_file_search_replace
status: success
filePath: /Users/long/Desktop/dart/test.dart
changes: undefined
现在运行文件验证代码正确性
toolName: todo_write
status: success
Todos updated: 3 items
toolName: run_command
status: success
command: dart run /Users/long/Desktop/dart/test.dart undefined
代码运行成功!
toolName: todo_write
status: success
Todos updated: 3 items
已完成 Map 知识点的补充!文件现在包含 11 个分区,覆盖了 Dart Map 的完整知识体系:
| # | 分区 | 关键知识点 |
|---|---|---|
| 1 | 基础用法 | 创建、赋值、删除、遍历、containsKey、clear |
| 2 | 类型安全的 Map | 泛型 Map<K, V>、Map<String, dynamic> |
| 3 | Map 的创建方式 | 字面量、工厂构造、Map.from、Map.of、Map.unmodifiable、Map.identity |
| 4 | 查询操作 | containsKey、containsValue、[] 取值、length、isEmpty、isNotEmpty |
| 5 | 遍历操作 | forEach、keys、values、entries (MapEntry) |
| 6 | 增删改操作 | addAll、addEntries、putIfAbsent、update、updateAll、remove、removeWhere、clear |
| 7 | Map 的变换 | map() 转换、entries.where 过滤、排序(列表排序再转回 Map) |
| 8 | 级联操作符 | .. 链式操作 |
| 9 | 扩展操作符 | ... 展开合并 Map |
| 10 | MapEntry | 独立的键值对对象 |
| 11 | 常见属性 | first、last、keys、values、entries |
dart
void main(List<String> args) {
// ==================== 1. 基础用法 ====================
print('===== 1. 基础用法 =====');
Map m = {"name": "张三", "age": 20};
m["age"] = 200;
print(m);
m["addr"] = "China";
print(m);
m.remove("addr");
print(m);
m.remove("addr");
print(m);
m.forEach((k, v) {
print("$k $v");
});
print(m.containsKey("name"));
m.clear();
print(m);
// ==================== 2. 类型安全的 Map(泛型) ====================
print('\n===== 2. 类型安全的 Map =====');
Map<String, int> scores = {"数学": 95, "语文": 88, "英语": 92};
print(scores);
// scores["物理"] = "优秀"; // 编译错误:类型不匹配
Map<String, dynamic> person = {"name": "李四", "age": 25, "height": 1.75};
print(person);
// ==================== 3. Map 的创建方式 ====================
print('\n===== 3. Map 的创建方式 =====');
// 字面量
Map<String, int> a = {"x": 1, "y": 2};
print('字面量: $a');
// 工厂构造函数
Map<String, int> b = Map<String, int>();
b["one"] = 1;
print('工厂构造: $b');
// Map.from - 从其他 Map 创建
Map<String, int> c = Map.from(a);
print('Map.from: $c');
// Map.of - 从其他 Map 创建(类型更严格)
Map<String, int> d = Map.of(a);
print('Map.of: $d');
// Map.unmodifiable - 创建不可修改的 Map
Map<String, int> e = Map.unmodifiable(a);
print('Map.unmodifiable: $e');
// e["z"] = 3; // 运行时错误:不可修改
// Map.identity - 使用身份比较的 Map
Map<String, int> f = Map.identity();
print('Map.identity: $f');
// ==================== 4. 查询操作 ====================
print('\n===== 4. 查询操作 =====');
Map<String, int> q = {"a": 1, "b": 2, "c": 3};
print('containsKey("a"): ${q.containsKey("a")}');
print('containsValue(2): ${q.containsValue(2)}');
print('["a"]: ${q["a"]}');
print('["x"] (不存在): ${q["x"]}'); // 返回 null
print('length: ${q.length}');
print('isEmpty: ${q.isEmpty}');
print('isNotEmpty: ${q.isNotEmpty}');
// ==================== 5. 遍历操作 ====================
print('\n===== 5. 遍历操作 =====');
Map<String, int> t = {"苹果": 10, "香蕉": 5, "橙子": 8};
// forEach 遍历
t.forEach((k, v) => print('$k: $v'));
// 遍历 keys
print('keys: ${t.keys.toList()}');
for (var k in t.keys) {
print('key: $k');
}
// 遍历 values
print('values: ${t.values.toList()}');
for (var v in t.values) {
print('value: $v');
}
// 遍历 entries (MapEntry)
for (var e in t.entries) {
print('entry: ${e.key} = ${e.value}');
}
// ==================== 6. 增删改操作 ====================
print('\n===== 6. 增删改操作 =====');
Map<String, int> g = {"red": 1, "green": 2};
// addAll - 合并另一个 Map
g.addAll({"blue": 3, "yellow": 4});
print('addAll: $g');
// addEntries - 合并 MapEntry 列表
g.addEntries([MapEntry("purple", 5), MapEntry("white", 6)]);
print('addEntries: $g');
// putIfAbsent - 仅当 key 不存在时设置值
g.putIfAbsent("black", () => 7);
g.putIfAbsent("red", () => 99); // 不会覆盖已存在的值
print('putIfAbsent: $g');
// update - 更新指定 key 的值
g.update("red", (v) => v + 10);
g.update("pink", (v) => v + 10, ifAbsent: () => 100);
print('update: $g');
// updateAll - 批量更新所有值
g.updateAll((k, v) => v * 2);
print('updateAll: $g');
// remove - 删除指定 key
g.remove("white");
print('remove: $g');
// removeWhere - 条件删除
g.removeWhere((k, v) => v > 20);
print('removeWhere(v>20): $g');
// clear - 清空
g.clear();
print('clear: $g');
// ==================== 7. Map 的变换 ====================
print('\n===== 7. Map 的变换 =====');
Map<String, int> src = {"a": 1, "b": 2, "c": 3};
// map 转换为新 Map
Map<String, String> mapped = src.map((k, v) => MapEntry(k.toUpperCase(), '值:$v'));
print('map 转换: $mapped');
// 过滤
Map<String, int> filtered = Map.fromEntries(src.entries.where((e) => e.value > 1));
print('filter 过滤: $filtered');
// 排序(Dart 没有内置排序,需转为列表排序再转回 Map)
Map<String, int> unsorted = {"c": 30, "a": 10, "b": 20};
var sortedEntries = unsorted.entries.toList()
..sort((a, b) => a.value.compareTo(b.value));
Map<String, int> sorted = Map.fromEntries(sortedEntries);
print('按 value 排序: $sorted');
// ==================== 8. 级联操作符 ====================
print('\n===== 8. 级联操作符 =====');
Map<String, int> cascade = {}
..["x"] = 10
..["y"] = 20
..["z"] = 30;
print('级联操作: $cascade');
// ==================== 9. 扩展操作符(...) ====================
print('\n===== 9. 扩展操作符 =====');
Map<String, int> base = {"a": 1, "b": 2};
Map<String, int> extended = {
...base,
"c": 3,
"d": 4,
};
print('扩展操作符: $extended');
// ==================== 10. MapEntry ====================
print('\n===== 10. MapEntry =====');
MapEntry<String, int> entry = MapEntry("test", 42);
print('key: ${entry.key}, value: ${entry.value}');
// ==================== 11. 常见属性 ====================
print('\n===== 11. 常见属性 =====');
Map<String, int> props = {"x": 1, "y": 2, "z": 3};
print('first: ${props.keys.first} => ${props[props.keys.first]}');
print('last: ${props.keys.last} => ${props[props.keys.last]}');
print('isEmpty: ${props.isEmpty}');
print('isNotEmpty: ${props.isNotEmpty}');
print('keys: ${props.keys}');
print('values: ${props.values}');
print('entries: ${props.entries}');
}
dynamic
dart
void main(List<String> args) {
var a = 20;
print(a.runtimeType); // int
// 编译错误,
// a = "hello";
//dynamic可以赋值任意类型
dynamic a1 = 20;
print(a1.runtimeType); // int
a1 = "Hello";
print(a1.runtimeType); // String
// 跳过检查,运行会报错
// print(a1 + 300);
// ==================== dynamic 知识点 ====================
// 1. dynamic 与 var、Object 的区别
// var: 编译时推断类型,之后不可改变类型
// Object: 所有类型的基类,需要类型转换才能访问特定方法
// dynamic: 编译时跳过类型检查,运行时检查类型
var b = 10;
// b = "hello"; // 编译错误,var推断后类型固定
Object obj = 10;
// obj + 5; // 编译错误,Object类型没有+运算符
(obj as int) + 5; // 需要显式类型转换
dynamic d = 10;
d + 5; // 编译通过,运行时检查
d = "hello"; // 可以赋值任意类型
// 2. dynamic 在集合中的使用
List<dynamic> dynamicList = [1, "hello", true, 3.14];
dynamicList.add(null); // 可以添加任意类型
print("dynamicList: $dynamicList");
// 3. dynamic 作为函数参数
void printDynamic(dynamic value) {
// 运行时检查类型
if (value is int) {
print("是整数: $value");
} else if (value is String) {
print("是字符串: $value");
} else {
print("其他类型: $value");
}
}
printDynamic(42);
printDynamic("Dart");
printDynamic([1, 2, 3]);
// 4. dynamic 的常见使用场景
// - 解析JSON数据
// - 与JavaScript互操作
// - 需要高度灵活性的场景
// 模拟JSON解析
Map<String, dynamic> json = {
"name": "张三",
"age": 25,
"scores": [90, 85, 88]
};
print("JSON解析示例: ${json['name']}, 年龄: ${json['age']}");
// 5. dynamic 的风险
dynamic risky;
// risky.someMethod(); // 编译通过,运行时抛出 NoSuchMethodError
// risky + 10; // 编译通过,运行时可能出错
// 安全的使用方式:先检查类型
if (risky is String) {
print(risky.length);
} else if (risky is int) {
print(risky + 10);
}
// 6. dynamic 与泛型
dynamic getValue<T>(T value) {
return value; // 返回类型自动推断为dynamic
}
var result1 = getValue<int>(100);
var result2 = getValue<String>("hello");
print("泛型示例: $result1, $result2");
// ==================== 最佳实践 ====================
// ✅ 避免滥用 dynamic,优先使用具体类型
// ✅ 使用 dynamic 时,添加运行时类型检查
// ✅ JSON解析等必要场景使用
// ❌ 不要用 dynamic 逃避类型系统
}