news_vm.dart 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import 'package:cpt_community/respository/common_newsfeed.dart';
  2. import 'package:cs_resources/generated/assets.dart';
  3. import 'package:domain/entity/newsfeed_news_entity.dart';
  4. import 'package:flutter/cupertino.dart';
  5. import 'package:plugin_basic/provider/user_config/user_config_service.dart';
  6. import 'package:plugin_platform/engine/toast/toast_engine.dart';
  7. import 'package:riverpod_annotation/riverpod_annotation.dart';
  8. import 'package:router/ext/auto_router_extensions.dart';
  9. import 'package:shared/utils/ext_dart.dart';
  10. import 'package:shared/utils/log_utils.dart';
  11. import 'package:widgets/load_state_layout.dart';
  12. import 'package:widgets/widget_export.dart';
  13. import 'package:easy_refresh/easy_paging.dart';
  14. import '../../../router/page/community_page_router.dart';
  15. import '../community_pageview_idx_data.dart';
  16. import '../community_vm.dart';
  17. import '../newsfeed_detail/newsfeed_detail_page.dart';
  18. import '../newsfeed_detail/newsfeed_detail_vm.dart';
  19. import 'news_state.dart';
  20. part 'news_vm.g.dart';
  21. @riverpod
  22. class NewsVm extends _$NewsVm {
  23. late CommonNewsFeedRespository commonNewsFeedRespositoryInstance;
  24. int _page = 1; // 当前页
  25. int _limit = 10; // 每页数量
  26. int _count = 0; // 总条数
  27. Map<String, dynamic> _queryParams = {
  28. 'keyword': null,
  29. 'is_liked': null,
  30. };
  31. bool _needShowPlaceholder = false; //是否展示LoadingView
  32. // Scroll 控制器
  33. final ScrollController scrollController = ScrollController();
  34. // Refresh 控制器
  35. final EasyRefreshController refreshController = EasyRefreshController(
  36. controlFinishRefresh: true, //允许刷新
  37. controlFinishLoad: true, //允许加载
  38. );
  39. NewsState initState() {
  40. return NewsState(
  41. list: []
  42. );
  43. }
  44. @override
  45. NewsState build(){
  46. // 引入数据仓库
  47. commonNewsFeedRespositoryInstance = ref.read(commonNewsFeedRespositoryProvider);
  48. final state = initState();
  49. Log.d("--------------------------build---------------------");
  50. return state;
  51. }
  52. //刷新页面状态
  53. void changeLoadingState(LoadState loadState, String? errorMsg) {
  54. state = state.copyWith(
  55. loadingState: loadState,
  56. errorMessage: errorMsg
  57. );
  58. }
  59. // 初始化页面数据
  60. initPageData() {
  61. Log.d("----news_vm-----initPageData ${state.loadingState}");
  62. onRefresh();
  63. }
  64. // 上拉加载 更多
  65. Future loadMore() async {
  66. Log.d("----news_vm-----loadMore");
  67. _page++;
  68. getListData(isLoadMore: true);
  69. }
  70. // 下拉刷新
  71. Future onRefresh() async {
  72. // 当前pageView 页面正处于显示状态
  73. Log.d("----news_vm-----onRefresh ");
  74. // await Future.delayed(const Duration(seconds: 2));
  75. _page = 1;
  76. getListData();
  77. }
  78. // 手动进行刷新
  79. Future triggerRefresh() async {
  80. Log.d("trggerRefresh");
  81. refreshController.callRefresh();
  82. }
  83. // 重试请求
  84. Future retryRequest() async {
  85. _page = 1;
  86. _needShowPlaceholder = true;
  87. getListData();
  88. // refreshController.callRefresh();
  89. }
  90. // 手动进行刷新
  91. Future directRefresh() async {
  92. state = state.copyWith(list:[]);
  93. // 注意:由于 nestedscrollview 嵌套easyfresh 组件 refreshController.callRefresh() 自动刷新只能滚动顶部但是不会触发下拉刷新,这里调用是 用到了将其滚动到顶部的作用,进而刷新操作主动掉接口
  94. // https://github.com/xuelongqy/flutter_easy_refresh/issues/692
  95. // refreshController.callRefresh();
  96. refreshController.resetFooter();
  97. _page = 1;
  98. _needShowPlaceholder = true;
  99. getListData();
  100. }
  101. // 获取list 列表数据
  102. Future getListData<T>({bool? isLoadMore}) async {
  103. Log.d("getListData _needShowPlaceholder: $_needShowPlaceholder");
  104. if (_needShowPlaceholder) {
  105. changeLoadingState(LoadState.State_Loading, null);
  106. }
  107. try {
  108. //请求网络
  109. Map<String, dynamic> params = {
  110. "page": _page,
  111. "limit": _limit,
  112. };
  113. Log.d("请求参数------$params");
  114. final result = await commonNewsFeedRespositoryInstance.fetchNewsList(params);
  115. //校验成功失败
  116. if (result.isSuccess) {
  117. handlerResultList((result.data as NewsfeedNewsEntity).list, isLoadMore ?? false);
  118. } else {
  119. String errorMessage = result.errorMsg!;
  120. changeLoadingState(LoadState.State_Error, errorMessage);
  121. ToastEngine.show(result.errorMsg ?? "Network Load Error");
  122. }
  123. } catch (e) {
  124. ToastEngine.show("Error: $e");
  125. }
  126. _needShowPlaceholder = false;
  127. }
  128. void handlerResultList(List<NewsfeedNewsList>? list, bool isLoadMore) {
  129. if (list != null && list.isNotEmpty) {
  130. //有数据,判断是刷新还是加载更多的数据
  131. if (_page == 1) {
  132. refreshController.resetFooter();
  133. //刷新的方式
  134. state.list!.clear();
  135. state.list!.addAll(list.map((item) => item.toJson()).toList());
  136. refreshController.finishRefresh();
  137. //更新展示的状态
  138. changeLoadingState(LoadState.State_Success, null);
  139. } else {
  140. //加载更多
  141. final allList = state.list;
  142. allList!.addAll(list.map((item) => item.toJson()).toList());
  143. state = state.copyWith(list: allList);
  144. refreshController.finishLoad();
  145. }
  146. } else {
  147. if (_page == 1) {
  148. //展示无数据的布局
  149. state.list!.clear();
  150. changeLoadingState(LoadState.State_Empty, null);
  151. refreshController.finishRefresh();
  152. } else {
  153. //展示加载完成,没有更多数据了
  154. if(state.list!.length == 0){
  155. changeLoadingState(LoadState.State_Empty, null);
  156. refreshController.finishLoad();
  157. }else {
  158. if(_needShowPlaceholder){
  159. changeLoadingState(LoadState.State_Success, null);
  160. }
  161. }
  162. //更新展示的状态
  163. refreshController.finishLoad(IndicatorResult.noMore);
  164. }
  165. }
  166. }
  167. // 点赞/取消点赞
  168. Future handlerLikeClick(int id, bool isLike, int? itemidx) async {
  169. try {
  170. List<Map<String, dynamic>> listCopyDta = List.from(state.list!);
  171. final result = await commonNewsFeedRespositoryInstance.fetchLikeClick({
  172. "id": id,
  173. });
  174. if (result.isSuccess) {
  175. if(itemidx != null){
  176. // 修改 listCopyDta[itemIdx] 中的 like 状态 和 likes_count
  177. listCopyDta![itemidx]['liked'] = !isLike;
  178. if(isLike){
  179. // 取消点赞
  180. if(listCopyDta![itemidx]['likes_count']>0){
  181. listCopyDta![itemidx]['likes_count'] = listCopyDta![itemidx]['likes_count'] - 1;
  182. }
  183. }else {
  184. listCopyDta![itemidx]['likes_count'] = listCopyDta![itemidx]['likes_count'] + 1;
  185. }
  186. }else {
  187. // 详情中的点赞 需要找到对应的 item 进行 修改 like 和 likes_count
  188. listCopyDta!.forEach((carditem) {
  189. if(carditem['id'] == id){
  190. carditem['liked'] = !isLike;
  191. if(isLike){
  192. // 取消点赞
  193. if(carditem['likes_count']>0){
  194. carditem['likes_count'] = carditem['likes_count'] - 1;
  195. }
  196. }else {
  197. carditem['likes_count'] = carditem['likes_count'] + 1;
  198. }
  199. }
  200. });
  201. }
  202. state = state.copyWith(list: listCopyDta);
  203. final String toastMsg = isLike ? "Cancel successfully": "Liked successfully";
  204. ToastEngine.show(toastMsg);
  205. return true;
  206. }else {
  207. return false;
  208. }
  209. }catch(error) {
  210. return false;
  211. }
  212. }
  213. // 点击 like comments share
  214. Future<bool?> handlerClickActionBtn(String? actionStr, Map<String, dynamic> item, int? itemidx) async{
  215. final id = item['id'];
  216. final liked = item.getValue('liked', false);
  217. switch (actionStr) {
  218. case 'like':
  219. return await handlerLikeClick(id, liked, itemidx);
  220. case 'comments':
  221. Log.d("点击了 评论");
  222. handlerGotoDetail(null, id);
  223. break;
  224. case 'share':
  225. Log.d("点击了 分享");
  226. handlerGotoDetail(null, id);
  227. break;
  228. default:
  229. Log.d("点击了卡片");
  230. handlerGotoDetail(null, id);
  231. break;
  232. }
  233. }
  234. // 关注/取消关注
  235. Future<bool> handlerFollow(BuildContext? context, int to_user_id,int cardId, bool isFollow) async{
  236. Log.d("点击了 关注");
  237. try {
  238. final result = await commonNewsFeedRespositoryInstance.handlerFollowOrCancel({
  239. "to_user_id": to_user_id,
  240. });
  241. if(result.isSuccess){
  242. // 修改cardId 对应的 card item 的 account 里面的 followed
  243. if(cardId!=null){
  244. final listCopyDta = List<Map<String, dynamic>>.from(state.list!);
  245. listCopyDta!.forEach((carditem) {
  246. if(carditem['id'] == cardId){
  247. carditem['account']['followed'] = !carditem['account']['followed'];
  248. }
  249. });
  250. state = state.copyWith(list: listCopyDta);
  251. }
  252. // 同步用户信息
  253. UserConfigService.getInstance().refreshUserInfo();
  254. return true;
  255. }else {
  256. return false;
  257. }
  258. }catch(error){
  259. Log.d("error: $error");
  260. return false;
  261. }
  262. }
  263. // 设置当前的 _queryParams
  264. setCurrentQueryParams(Map<String, dynamic> params){
  265. _queryParams.addAll(params);
  266. }
  267. // 获取当前的 _queryParams
  268. Map<String, dynamic> getCurrentQueryParams(String? key){
  269. if(key!=null && key!.isNotEmpty){
  270. return _queryParams[key]??{};
  271. }
  272. return _queryParams;
  273. }
  274. // 去详情页面
  275. void handlerGotoDetail(BuildContext? context, int id){
  276. Log.d("去详情页面");
  277. appRouter.push(NewsfeedDetailPageRoute(id: id, type: 'news'));
  278. }
  279. }