示例工程 ch08-advanced

ch08-advanced/lib/pub_packages.dart

dart · 1.5 KB

/// 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);