跳到正文
教程首页
DartCH 03ch03_types_collections

ch03-types-collections

Dart 类型系统与集合:类、泛型、List/Map/Set、null 安全。完整工程共 10 个文件,其中 10 个文本源文件可在下面在线阅读。

10

在线文本文件

1,160

源码行数

dart / yaml / text

语言

17 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

darttextyaml

10 text files · 1,160 lines

dartbin/ch03_types_collections.dart
// 第 3 章可运行入口:`dart run`。
import 'package:ch03_types_collections/collections.dart';
import 'package:ch03_types_collections/generics.dart';
import 'package:ch03_types_collections/money.dart';
import 'package:ch03_types_collections/null_safety.dart';
import 'package:ch03_types_collections/shapes.dart';

void main() {
  print('--- 1. 值类型:Money ---');
  const coffee = Money(2050);
  final tea = Money.fromYuan(20.5);
  print('coffee = $coffee, tea = $tea');
  print('coffee == tea ? ${coffee == tea}  identical? ${identical(coffee, tea)}');
  print('coffee + tea = ${coffee + tea}');
  print('放进 Set 会被去重: ${<Money>{coffee, tea, Money(100)}.length} 个');

  print('\n--- 2. 增强枚举 ---');
  for (final p in Planet.values) {
    print('${p.label}: g = ${p.surfaceGravity.toStringAsFixed(2)} m/s²');
  }

  print('\n--- 3. sealed 类 + 穷尽 switch ---');
  const shapes = <Shape2>[
    Circle(1),
    Rectangle(3, 4),
    Rectangle.square(2),
    Triangle(6, 5),
  ];
  for (final s in shapes) {
    print('${label(s)} → ${s.area.toStringAsFixed(2)}');
  }
  print('总面积 = ${totalArea(shapes).toStringAsFixed(2)}');
  const named = NamedCircle(2, '大圆');
  print('${named.describe()} · compareTo: ${named.compareTo(const NamedCircle(1, '小圆'))}');

  print('\n--- 4. 泛型 ---');
  print('maxOf([3,1,4,1,5]) = ${maxOf(<int>[3, 1, 4, 1, 5])}');
  print('maxOf(["pear","apple"]) = ${maxOf(<String>['pear', 'apple'])}');
  print('Box(2).map(x*10) = ${const Box<int>(2).map((int x) => x * 10)}');
  print('Pair(1,"a").swapped = ${const Pair<String, int>('a', 1).swapped}');
  print('isIntList(<int>[1]) = ${isIntList(<int>[1])}, isIntList(<String>["1"]) = ${isIntList(<String>['1'])}');
  print('sumOf([1,2,3]) = ${sumOf(<int>[1, 2, 3], seed: 0)}');
  print('sumOf([1.5,2.5]) = ${sumOf(<double>[1.5, 2.5], seed: 0.0)}');
  try {
    addDouble(widenToNum(<int>[1, 2]));
  } on TypeError catch (e) {
    print('协变写入被运行期拦下: ${e.runtimeType}');
  }

  print('\n--- 5. 集合 ---');
  print('偶数的平方: ${squaresOfEven(<int>[1, 2, 3, 4, 5, 6])}');
  print('按长度分组: ${groupByLength(<String>['go', 'dart', 'c', 'rust', 'flutter'])}');
  print('词频: ${wordCounts('the quick the lazy dog the')}');
  print('去重: ${uniqueWords('Go go DART dart C')}');
  print('降序: ${sortedDescending(<int>[3, 1, 4, 1, 5])}');
  print('range(5) = ${range(5)}, fixedSlots = ${fixedSlots()}');
  print('tags = ${buildTags(starred: true, extra: <String>['a'], more: <String>['b'])}');
  print('inventory = ${inventory()}');

  print('\n--- 6. null 安全 ---');
  print('displayName(null) = ${displayName(null)}');
  print('displayName("  Ada  ") = ${displayName('  Ada  ')}');
  print('shout(null) = ${shout(null)}, shout("hi") = ${shout('hi')}');
  print('firstWord("  ") = ${firstWord('  ')}');
  print('cityOfUser(嵌套 map) = ${cityOfUser(<String, Object?>{
        'address': <String, Object?>{'city': '上海'},
      })}');
  print('cityOfUser(null) = ${cityOfUser(null)}');
  final cfg = LazyConfig();
  print('dbPath = ${cfg.dbPath}, 计算次数 = ${cfg.computeCount}');
  print('再次读取 dbPath = ${cfg.dbPath}, 计算次数 = ${cfg.computeCount}');
  try {
    uninitializedLate();
  } catch (e) {
    print('late 未初始化: ${e.runtimeType}');
  }
  try {
    unsafeBang(null);
  } on TypeError catch (e) {
    print('! 遇到 null: ${e.runtimeType}');
  }
  print('lookup(不存在) = ${lookup(<String, int>{'a': 1}, 'b')}');
}

代码构成:dart 27 KB · text 11 KB · yaml 400 B

本地运行

zip → 解压 → 执行
$cd examples/ch03-types-collections && dart pub get && dart run

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • dart analyze(0 告警)、dart test(32 个用例全绿)
查看全部示例