import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:news_app/constant/api_const.dart'; import '../http/http_util.dart'; import '../http/model_parser.dart'; import '../model/news_detail_model.dart'; import '../ui/me/user_favorite_page.dart'; class NewsDetailProvider extends AutoDisposeNotifier { @override NewsDetailModel build() { return NewsDetailModel(); } Future fetchNewsDetail(String contentId) async { var jsonData = await HttpUtil().get( apiNewsDetail, //视频固定展示4个 queryParameters: {"contentId": contentId}, ); final response = ModelParser.parseObject( jsonData, NewsDetailModel.fromJson, ); state = response; } Future fetchNewsShare({required String? contentId}) async { if (contentId == null || contentId.isEmpty) { return; } await HttpUtil().get( apiNewsShare, queryParameters: {"contentId": contentId}, ); } Future fetchNewsLike({ required String? contentId, required bool current, }) async { if (contentId == null || contentId.isEmpty) { return; } final jsonData = await HttpUtil().get( current ? apiNewsCancelLike : apiNewsLike, queryParameters: {"contentId": contentId}, ); if (jsonData == true) { if (current) { state = state.copyWith( likeCount: (state.likeCount ?? 1) - 1, //默认1是为了防止出现负数 isLiked: false, ); } else { //修改成功后,把 likeCount+1 state = state.copyWith( likeCount: (state.likeCount ?? 0) + 1, isLiked: true, ); } } } Future fetchNewsFavorite({ required String? contentId, required bool current, }) async { if (contentId == null || contentId.isEmpty) { return; } final jsonData = await HttpUtil().get( current ? apiNewsCancelFavorite : apiNewsFavorite, queryParameters: {"contentId": contentId}, ); if (jsonData == true) { //修改成功后,把favoriteCount+1 if (current) { //修改成功后,把favoriteCount-1 state = state.copyWith( favoriteCount: (state.favoriteCount ?? 1) - 1, //默认1是为了防止出现负数 isFavorite: false, ); ref .read(favoriteNewsProvider.notifier) .removeItemByContentId(contentId); } else { state = state.copyWith( favoriteCount: (state.favoriteCount ?? 0) + 1, isFavorite: true, ); } } } }