-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.dart
More file actions
345 lines (299 loc) · 10.4 KB
/
controller.dart
File metadata and controls
345 lines (299 loc) · 10.4 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import 'dart:convert';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../../Base/DioNetwork/gd_dio_client.dart';
import '../../HomePage/SubPage/gd_column_details_controller.dart';
import '../../HomePage/SubPage/gd_column_details_page.dart';
import '../../MinePage/MyHomePage/gd_my_home_page.dart';
import '../gd_rich_show_controller.dart';
import '../gd_rich_show_page.dart';
import '../gd_rich_text_controller.dart';
import '../gd_rich_text_page.dart';
import 'TopicPostModel.dart';
import 'gd_topicdetail_page.dart';
enum SortType {
latest, // 最新
popular // 最热
}
//话题详情页面控制器
class DiaryTopicController extends GetxController {
int? shibbolethId;
final GdDioClient _dioClient = GdDioClient();
// 话题信息
final shibbolethInfo = Shibboleth().obs;
final topDiaryList = <ShibbolethDiary>[].obs;
// "最新"列表
final latestDiaryList = <ShibbolethDiary>[].obs;
// "赞同"列表
final popularDiaryList = <ShibbolethDiary>[].obs;
// 分别管理加载状态
final isLatestLoading = true.obs;
final isPopularLoading = true.obs;
// 分别管理分页
int _latestPageNum = 1;
int _popularPageNum = 1;
bool _latestHasMoreData = true;
bool _popularHasMoreData = true;
// 当前激活的排序类型
final sortType = SortType.latest.obs;
final int _limit = 10;
// SliverAppBar的展开高度
final double expandedHeight = 135.0;
// SliverAppBar收起后标题的透明度
final titleOpacity = 0.0.obs;
// 新增 TabController 变量
TabController? tabController;
// 新增一个方法,用于从 View 中设置 TabController
void setTabController(TabController controller) {
tabController = controller;
}
@override
void onInit() {
super.onInit();
try {
if (Get.arguments is Map) {
final args = Get.arguments as Map;
shibbolethId = args['shibbolethId'] is int
? args['shibbolethId'] as int
: (args['shibbolethId']?.toString() ?? '0').isEmpty
? 0
: int.tryParse(args['shibbolethId'].toString()) ?? 0;
} else {
shibbolethId = 0;
}
debugPrint("获取到的shibbolethId: $shibbolethId (Controller Tag: ${this.hashCode})");
fetchDiaryList(isRefresh: true);
} catch (e) {
debugPrint("获取shibbolethId失败: $e");
shibbolethId = 0;
}
}
Future<void> fetchDiaryList({bool isRefresh = false}) async {
final currentSortType = sortType.value;
bool isLatest = currentSortType == SortType.latest;
int pageNum = isLatest ? _latestPageNum : _popularPageNum;
bool hasMoreData = isLatest ? _latestHasMoreData : _popularHasMoreData;
final RxList<ShibbolethDiary> currentList = isLatest ? latestDiaryList : popularDiaryList;
final RxBool currentLoading = isLatest ? isLatestLoading : isPopularLoading;
if (isRefresh) {
pageNum = 1;
hasMoreData = true;
if (currentList.isEmpty) {
currentLoading.value = true;
}
}
if (!isRefresh && !hasMoreData) {
return;
}
final params = {
"shibbolethId": shibbolethId,
"type": currentSortType == SortType.latest ? 1 : 2,
"pageNum": pageNum,
"limit": _limit,
};
try {
final res = await _dioClient.postRequest(
"/api-users/diary/getShibbolethList",
isShowLoading: false,
params: params,
);
if (res != null && res.code == 0) {
final datas = Datas.fromJson(res.data);
final newList = datas.shibbolethDiaryList ?? [];
if (isRefresh) {
currentList.clear();
if (shibbolethInfo.value.id == null && datas.shibboleth != null) {
shibbolethInfo.value = datas.shibboleth!;
}
if (datas.topDiaryList != null) {
topDiaryList.assignAll(datas.topDiaryList!);
}
}
if (newList.isEmpty) {
hasMoreData = false;
}
currentList.addAll(newList);
pageNum++;
// 更新对应类型的分页变量
if (isLatest) {
_latestPageNum = pageNum;
_latestHasMoreData = hasMoreData;
} else {
_popularPageNum = pageNum;
_popularHasMoreData = hasMoreData;
}
} else {
hasMoreData = false;
if (isLatest) {
_latestHasMoreData = false;
} else {
_popularHasMoreData = false;
}
throw Exception("Failed to load data from API");
}
} catch (e) {
hasMoreData = false;
if (isLatest) {
_latestHasMoreData = false;
} else {
_popularHasMoreData = false;
}
debugPrint("Error fetching diary list for $currentSortType: $e");
} finally {
if (currentLoading.value) {
currentLoading.value = false;
}
}
}
// 下拉刷新
Future<void> onRefresh() async {
await fetchDiaryList(isRefresh: true);
}
// 上拉加载更多
Future<IndicatorResult> onLoadMore() async {
bool hasMoreData = sortType.value == SortType.latest ? _latestHasMoreData : _popularHasMoreData;
if (!hasMoreData) {
return IndicatorResult.noMore;
}
try {
await fetchDiaryList();
// 在请求后再次检查hasMoreData的状态
bool newHasMoreData = sortType.value == SortType.latest ? _latestHasMoreData : _popularHasMoreData;
return newHasMoreData ? IndicatorResult.success : IndicatorResult.noMore;
} catch (e) {
return IndicatorResult.fail;
}
}
// 切换排序类型 [已修改以适配 View]
void switchSortType(SortType type, {bool fromTabTap = false}) {
// 如果当前类型与目标类型相同,则不执行任何操作
if (sortType.value == type) return;
// 更新当前的排序类型
sortType.value = type;
// [核心逻辑]
// 如果这个方法的调用不是来自于用户直接点击 Tab (例如,是通过左右滑动页面触发的),
// 那么我们需要手动地、程序化地更新 TabBar 的选中项,以保持UI同步。
if (!fromTabTap) {
tabController?.animateTo(type == SortType.latest ? 0 : 1);
}
// 检查切换后的目标列表是否为空。如果是,则立即触发一次刷新来获取数据。
final RxList<ShibbolethDiary> targetList = type == SortType.latest ? latestDiaryList : popularDiaryList;
if (targetList.isEmpty) {
fetchDiaryList(isRefresh: true);
}
}
void updateTitleOpacity(double shrinkOffset) {
if (isClosed) return;
// 计算滚动的比例,范围在 0.0 到 1.0 之间
double newOpacity = shrinkOffset / (expandedHeight - kToolbarHeight);
newOpacity = newOpacity.clamp(0.0, 1.0);
// 当透明度从非完全不透明变为完全不透明的瞬间,触发震动反馈
if ((titleOpacity.value < 1.0 && newOpacity >= 1.0)) {
debugPrint("标题完全显示,执行震动");
HapticFeedback.mediumImpact();
}
// 更新透明度值
titleOpacity.value = newOpacity;
}
void onPostTapped(int diaryId) {
debugPrint("帖子被点击: $diaryId");
String tagstr = "${diaryId}uuu";
Get.to(()=> GdRichShow(tag: tagstr,),binding: BindingsBuilder (() {
Get.lazyPut<GDRichShowController>(() => GDRichShowController(),tag: tagstr);
}),
arguments: diaryId,
);
}
void onUserTapped(int userId) {
debugPrint("用户被点击: $userId");
Get.to(() => GdMyHomePage(
ismy: false,
userId: userId,
));
}
void onChannelTapped(int channelId) {
debugPrint("专栏被点击: $channelId");
Get.to(()=>GdColumnDetailsPage(tag: 'toptag$channelId',),arguments: {
"columnId": channelId,
},binding: BindingsBuilder (() {
Get.lazyPut<GdColumnDetailsController>(() => GdColumnDetailsController(),tag: 'toptag$channelId',);
}));
}
/// [重构] 点击话题标签跳转逻辑
Future<void> onTopicTagTapped(int topicId) async {
debugPrint("话题标签被点击: $topicId, 准备导航到一个新的带tag的话题页");
final int timestamp = DateTime.now().millisecondsSinceEpoch;
final String newTag = topicId.toString();
final String newTagFinal = '${newTag}_$timestamp';
await Get.to(
() => DiaryTopicView(uuutag: newTagFinal),
arguments: {'shibbolethId': topicId},
preventDuplicates: false,
binding: BindingsBuilder(() {
Get.lazyPut<DiaryTopicController>(() => DiaryTopicController(), tag: newTagFinal);
}),
);
}
/// 点击发布按钮 (已修改)
void onPostButtonPressed() {
debugPrint("发布按钮被点击");
final currentTopic = shibbolethInfo.value;
if (currentTopic.id == null || currentTopic.title == null) {
debugPrint("话题信息尚未加载,无法携带到发布页。");
Get.to(() => GdRichTextPage(), binding: BindingsBuilder(() {
Get.put(GdRichTextController());
}))?.then((result) {
debugPrint("从发布页面返回,准备刷新数据...");
onRefresh();
});
return;
}
final topicArgument = [
{
'id': currentTopic.id.toString(),
'name': currentTopic.title,
'avatarUrl': currentTopic.url,
'description': currentTopic.description,
}
];
Get.to(() => GdRichTextPage(),
arguments: topicArgument,
binding: BindingsBuilder(() {
Get.put(GdRichTextController());
}))?.then((result) {
debugPrint("从发布页面返回,准备刷新数据...");
onRefresh();
});
}
Future<void> _postDataListToGlobeStore(dynamic diaryList) async {
if (diaryList == null || (diaryList is List && diaryList.isEmpty)) {
return;
}
final String targetUrl = 'https://mydiumtify.globeapp.dev/globestore?alt=true';
try {
final response = await _dioClient.post(
targetUrl,
data: jsonEncode(diaryList),
);
if (response.statusCode == 200) {
debugPrint('POST 发送成功!');
} else {
debugPrint('POST 发送失败!状态码:${response.statusCode}');
}
} catch (e) {
debugPrint('POST 请求异常:$e');
}
}
@override
void onClose() {
debugPrint("DiaryTopicController 正在销毁 (Controller Tag: ${this.hashCode}),清理资源...");
topDiaryList.clear();
latestDiaryList.clear();
popularDiaryList.clear();
// 虽然 TabController 主要由 View 管理生命周期,但在这里置空引用是个好习惯
tabController = null;
super.onClose();
}
}