跳到正文
教程首页
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

dartlib/collections.dart
/// 集合:`List` / `Set` / `Map` 与它们的惯用法。
///
/// 关键差异(Go 程序员最容易忽略的一条):
/// **Dart 的 Map / Set 默认保持插入顺序**(LinkedHashMap / LinkedHashSet),
/// 而 Go 的 map 遍历顺序是随机的,C 里更没有"有序字典"这回事。
library;

/// `map` / `where` / `fold` 是链式的高阶函数,比手写循环短,但注意每步都会新建集合。
List<int> squaresOfEven(List<int> xs) =>
    xs.where((int x) => x.isEven).map((int x) => x * x).toList();

/// 分组:`Map<K, List<V>>` 是 Dart 里的标准做法(Go 里是 `map[K][]V`)。
Map<int, List<String>> groupByLength(List<String> words) {
  final result = <int, List<String>>{};
  for (final w in words) {
    // `putIfAbsent` / `??=` 都能避免手写"先判断 key 是否存在"。
    (result[w.length] ??= <String>[]).add(w);
  }
  return result;
}

/// 词频统计:`??=` 是 null-aware assignment,等价于 `if (m[k] == null) m[k] = 0`。
Map<String, int> wordCounts(String text) {
  final counts = <String, int>{};
  for (final raw in text.toLowerCase().split(RegExp(r'\s+'))) {
    final word = raw.replaceAll(RegExp(r'[^a-z0-9]'), '');
    if (word.isEmpty) continue;
    counts[word] = (counts[word] ?? 0) + 1;
  }
  return counts;
}

/// `Set` 去重;Dart 的 Set 用 `hashCode` + `==` 判重,与 C++ 的 unordered_set 同理。
Set<String> uniqueWords(String text) =>
    text.toLowerCase().split(RegExp(r'[^a-z]+')).where((String w) => w.isNotEmpty).toSet();

/// 排序:`sort` 是**原地**修改(像 Go 的 `sort.Ints`),
/// 所以要保留原序必须先 `[...]` 复制(Go 里是 `slices.Clone`)。
List<int> sortedDescending(List<int> xs) => [...xs]..sort((int a, int b) => b.compareTo(a));

/// 固定长度列表:初始化后不能增删,但能改元素——像 C 的 `int arr[3]`。
List<int> fixedSlots() => List<int>.filled(3, 0);

/// 生成序列:等价 Go 的 `for i := 0; i < n; i++ { append(...) }`。
List<int> range(int n) => List<int>.generate(n, (int i) => i);

/// 不可变视图:对它的任何写操作抛 `UnsupportedError`(C 的 `const` 数组 / Go 没有对应物)。
List<String> readOnlyTags() => List<String>.unmodifiable(<String>['dart', 'flutter']);

/// 集合推导(collection-for / collection-if / spread):Dart 独有的紧凑写法。
List<String> buildTags({
  bool starred = false,
  List<String> extra = const <String>[],
  List<String>? more,
}) =>
    [
      'dart',
      if (starred) 'starred', // collection-if
      for (final e in extra) 'extra:$e', // collection-for
      ...?more, // spread 可空集合:...? 遇到 null 直接跳过
    ];

/// 嵌套集合:`Map<String, Map<String, int>>` 在配置文件里很常见。
Map<String, Map<String, int>> inventory() => {
      'fruits': {'apple': 3, 'pear': 5},
      'tools': {'hammer': 1},
    };

代码构成: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 个用例全绿)
查看全部示例