news_vm.dart 8.9 KB

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