跳到正文
教程首页
DartCH 08ch08_advanced

ch08-advanced

Dart 进阶:mixin、extension、pub 包管理、isolate 并发。完整工程共 9 个文件,其中 9 个文本源文件可在下面在线阅读。

9

在线文本文件

919

源码行数

dart / yaml / text

语言

13 KB

打包体积

在线阅读源码

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

darttextyaml

9 text files · 919 lines

dartlib/pub_packages.dart
/// pub 包管理:这里演示一个真实依赖的用法。
///
/// `pubspec.yaml` 里声明 `collection: ^1.19.0`:
///   - `^` 是"兼容版本范围":>=1.19.0 <2.0.0(相当于 Go 的模块 major 版本语义);
///   - `pubspec.lock` 锁定精确版本,保证团队/CI 完全一致;
///   - `dart pub get` / `dart pub add` / `dart pub outdated` / `dart pub deps` 是日常命令。
///
/// 对照 Go:`go.mod` + `go.sum`;对照 C:pkg-config / vcpkg / 手工 git submodule。
library;

import 'package:collection/collection.dart';

/// `firstWhereOrNull` 是 `collection` 里最常用的补充:
/// Dart 内置的 `firstWhere` 找不到会抛 `StateError`,而 Go 里你写 `if !ok`。
int? findFirstEven(List<int> xs) => xs.firstWhereOrNull((int x) => x.isEven);

/// `groupBy` 直接给出 `Map<K, List<V>>`,省掉手写 `??=` 的那几行。
Map<bool, List<int>> splitBySign(List<int> xs) =>
    groupBy<int, bool>(xs, (int x) => x >= 0);

/// `sortedBy` / `sorted` 返回**新列表**,不像 `List.sort` 原地改。
List<String> namesSorted(List<String> names) => names.sorted();

/// `ListEquality`:给 List 提供**结构相等**。
/// ch03 讲过 Dart 的 `List ==` 是引用相等,`collection` 里的 equality 类就是标准解法。
bool sameNumbers(List<int> a, List<int> b) =>
    const ListEquality<int>().equals(a, b);

/// `IterableEquality` 还能比较集合、作为 Map 的 key 相等性使用。
bool sameSets(Set<String> a, Set<String> b) =>
    const SetEquality<String>().equals(a, b);

代码构成:dart 17 KB · text 11 KB · yaml 413 B

本地运行

zip → 解压 → 执行
$cd examples/ch08-advanced && dart pub get && dart run

这个 zip 里有什么

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

已验证

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