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/application/providers.dart171 行 · 6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/// 应用层:依赖注入(Riverpod providers)+ 派生状态 + 写操作。
///
/// 分层的依赖方向(单向):
/// presentation → application → domain ← data
/// 也就是:UI 只认识 providers;providers 只认识仓储接口;仓储实现是唯一 import drift/http 的地方。
library;
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import '../core/config.dart';
import '../data/database.dart';
import '../data/drift_bookmark_repository.dart';
import '../data/remote_api.dart';
import '../domain/bookmark.dart';
import '../domain/bookmark_repository.dart';
// ---------------------------------------------------------------------------
// 基础设施
// ---------------------------------------------------------------------------
final appConfigProvider = Provider<AppConfig>((Ref ref) => AppConfig.fromEnvironment());
final httpClientProvider = Provider<http.Client>((Ref ref) {
final http.Client client = http.Client();
ref.onDispose(client.close);
return client;
});
/// 生产:文件数据库;测试:`databaseProvider.overrideWithValue(AppDatabase.memory())`。
final databaseProvider = Provider<AppDatabase>((Ref ref) {
final AppDatabase db = AppDatabase.open();
ref.onDispose(db.close);
return db;
});
final remoteApiProvider = Provider<BookmarkRemoteApi>(
(Ref ref) => HttpBookmarkRemoteApi(
client: ref.watch(httpClientProvider),
config: ref.watch(appConfigProvider),
),
);
final repositoryProvider = Provider<BookmarkRepository>(
(Ref ref) => DriftBookmarkRepository(
ref.watch(databaseProvider),
ref.watch(remoteApiProvider),
),
);
// ---------------------------------------------------------------------------
// 状态
// ---------------------------------------------------------------------------
/// 全部书签(drift 的 watch → StreamProvider,任何写入都会自动刷新)。
final bookmarksProvider = StreamProvider<List<Bookmark>>(
(Ref ref) => ref.watch(repositoryProvider).watchAll(),
);
/// 搜索关键字:**防抖** 150ms。
///
/// 每敲一个字符就过滤一次 10k 条数据,会把输入框拖卡(ch17 性能部分)。
/// 防抖后"用户停止输入 150ms"才真正过滤,输入过程始终顺滑。
class SearchQuery extends Notifier<String> {
Timer? _timer;
@override
String build() {
ref.onDispose(() => _timer?.cancel());
return '';
}
void set(String value) {
_timer?.cancel();
_timer = Timer(const Duration(milliseconds: 150), () => state = value);
}
/// 需要立刻生效时用(比如点"清除"按钮)。
void setImmediately(String value) {
_timer?.cancel();
state = value;
}
}
final searchQueryProvider = NotifierProvider<SearchQuery, String>(SearchQuery.new);
/// 过滤后的列表:派生状态,自动随关键字与数据变化。
/// UI 不需要自己写 where,也不用担心"忘了刷新"。
final filteredBookmarksProvider = Provider<AsyncValue<List<Bookmark>>>((Ref ref) {
final String query = ref.watch(searchQueryProvider).trim().toLowerCase();
final AsyncValue<List<Bookmark>> all = ref.watch(bookmarksProvider);
return all.whenData((List<Bookmark> items) {
if (query.isEmpty) return items;
return items
.where((Bookmark b) =>
b.title.toLowerCase().contains(query) ||
b.note.toLowerCase().contains(query) ||
b.url.toLowerCase().contains(query))
.toList(growable: false);
});
});
/// 按 id 查单条:详情页用。数据源仍是同一个 stream,所以列表变了详情页也同步。
final bookmarkByIdProvider = Provider.family<AsyncValue<Bookmark?>, int>((Ref ref, int id) {
return ref.watch(bookmarksProvider).whenData((List<Bookmark> items) {
for (final Bookmark b in items) {
if (b.id == id) return b;
}
return null;
});
});
/// 同步状态:导入按钮的 loading / error 展示。
class SyncState {
const SyncState({this.running = false, this.error, this.lastImported});
final bool running;
final String? error;
final int? lastImported;
SyncState copyWith({bool? running, String? error, int? lastImported}) => SyncState(
running: running ?? this.running,
error: error,
lastImported: lastImported ?? this.lastImported,
);
}
class SyncNotifier extends Notifier<SyncState> {
@override
SyncState build() => const SyncState();
Future<void> run() async {
if (state.running) return; // 防重复点击
state = const SyncState(running: true);
try {
final int imported = await ref.read(repositoryProvider).importFromRemote(limit: 10);
state = SyncState(lastImported: imported);
} on SyncException catch (e) {
state = SyncState(error: e.message);
} on Object catch (e) {
state = SyncState(error: '$e');
}
}
}
final syncProvider = NotifierProvider<SyncNotifier, SyncState>(SyncNotifier.new);
// ---------------------------------------------------------------------------
// 写操作:UI 只调这些方法,不直接碰仓储
// ---------------------------------------------------------------------------
class BookmarkActions {
BookmarkActions(this._ref);
final Ref _ref;
BookmarkRepository get _repo => _ref.read(repositoryProvider);
Future<int> add(BookmarkDraft draft) => _repo.add(draft);
Future<void> toggleFavorite(Bookmark bookmark) =>
_repo.setFavorite(bookmark.id, favorite: !bookmark.favorite);
Future<void> delete(int id) => _repo.delete(id);
}
final bookmarkActionsProvider = Provider<BookmarkActions>((Ref ref) => BookmarkActions(ref));
代码构成: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** 构建均真实启动成功