跳到正文
教程首页
FlutterCH 16ch16_bookmarks

ch16-bookmarks

综合项目(上):架构设计、数据层、依赖注入。完整工程共 116 个文件,其中 76 个文本源文件可在下面在线阅读。

76

在线文本文件

5,837

源码行数

dart / c / yaml

语言

301 KB

打包体积

在线阅读源码

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

textdartxmljsonkotlin

76 text files · 5,837 lines

dartlib/src/domain/bookmark.dart
/// 领域实体:不依赖 Flutter、不依赖 drift/http。
///
/// 分层的关键:**领域层不知道数据从哪来**(SQLite?网络?内存?),
/// 所以它可以被任何数据源复用,也可以脱离框架单测。
library;

import 'package:flutter/foundation.dart' show immutable;

@immutable
class Bookmark {
  const Bookmark({
    required this.id,
    required this.title,
    required this.url,
    this.note = '',
    this.favorite = false,
    required this.createdAt,
  });

  final int id;
  final String title;
  final String url;
  final String note;
  final bool favorite;
  final DateTime createdAt;

  Bookmark copyWith({String? title, String? url, String? note, bool? favorite}) => Bookmark(
        id: id,
        title: title ?? this.title,
        url: url ?? this.url,
        note: note ?? this.note,
        favorite: favorite ?? this.favorite,
        createdAt: createdAt,
      );

  @override
  bool operator ==(Object other) =>
      other is Bookmark &&
      other.id == id &&
      other.title == title &&
      other.url == url &&
      other.note == note &&
      other.favorite == favorite &&
      other.createdAt == createdAt;

  @override
  int get hashCode => Object.hash(id, title, url, note, favorite, createdAt);

  @override
  String toString() => 'Bookmark($id, $title, favorite: $favorite)';
}

/// 新建书签的输入(还没有 id / createdAt)。
@immutable
class BookmarkDraft {
  const BookmarkDraft({required this.title, required this.url, this.note = ''});

  final String title;
  final String url;
  final String note;

  /// 表单校验:返回 null 表示合法。
  String? validate() {
    if (title.trim().isEmpty) return '标题不能为空';
    // 注意:不能用 hasAbsolutePath 判断——`https://a.test` 的 path 是空串,
    // hasAbsolutePath 为 false。正确的检查是 scheme + host。
    final Uri? uri = Uri.tryParse(url.trim());
    if (uri == null || uri.host.isEmpty || (uri.scheme != 'http' && uri.scheme != 'https')) {
      return '需要一个 http(s) 链接';
    }
    return null;
  }
}

代码构成:text 77 KB · dart 69 KB · xml 41 KB · json 4 KB

本地运行

zip → 解压 → 执行
$cd examples/ch16-bookmarks && flutter run -d macos

这个 zip 里有什么

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

已验证

  • flutter analyze 0 告警、flutter test 20 个用例全绿、debug 与 **release** 构建均真实启动成功
查看全部示例