import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:news_app/constant/api_const.dart'; import 'package:news_app/http/http_util.dart'; import 'package:news_app/model/topic_item_model.dart'; import '../http/model_parser.dart'; /// @author: bo.zeng /// @email: cnhbwds@gmail.com /// @date: 2025 2025/4/18 10:43 /// @description: class TopicListProvider extends Notifier { @override TopicItemModel build() { return TopicItemModel(); } Future fetchList({required int page,required String tid}) async { var jsonData = await HttpUtil().get( apiTopicList, queryParameters: tid.isEmpty ? {"pn": page, "ps": 10} : {"tid":tid ,"pn": page, "ps": 10}, ); final response = ModelParser.parseObject( jsonData, TopicItemModel.fromJson, ); final oldRecords = state.records ?? []; state = state.copyWith( total: response.total, size: response.size, current: response.current, pages: response.pages, records: page == 1 ? response.records : [...oldRecords, ...?response.records], ); } Future fetchTopicLike({ required String? contentId, required bool current, }) async { if (contentId == null || contentId.isEmpty) { return; } final jsonData = await HttpUtil().get( current ? apiTopicCancelLike : apiTopicLike, queryParameters: {"contentId": contentId}, ); if (jsonData == true) { //修改成功后,把state列表中的item likeCount+1 if (current) { state = state.copyWith( records: state.records?.map((topic) { if (topic.contentId == contentId) { return topic.copyWith( likeNum: (topic.likeNum ?? 1) - 1, isLiked: false, ); } return topic; }).toList(), ); } else { state = state.copyWith( records: state.records?.map((topic) { if (topic.contentId == contentId) { return topic.copyWith( likeNum: (topic.likeNum ?? 0) + 1, isLiked: true, ); } return topic; }).toList(), ); } } } Future fetchTopicFavorite({ required String? contentId, required bool current, }) async { if (contentId == null || contentId.isEmpty) { return; } final jsonData = await HttpUtil().get( current ? apiTopicCancelFavorite : apiTopicFavorite, queryParameters: {"contentId": contentId}, ); if (jsonData == true) { //修改成功后,把state列表中的item likeCount+1 if (current) { state = state.copyWith( records: state.records?.map((topic) { if (topic.contentId == contentId) { return topic.copyWith( favoriteCount: (topic.favoriteCount ?? 1) - 1, isFavorite: false, ); } return topic; }).toList(), ); } else { state = state.copyWith( records: state.records?.map((topic) { if (topic.contentId == contentId) { return topic.copyWith( favoriteCount: (topic.favoriteCount ?? 0) + 1, isFavorite: true, ); } return topic; }).toList(), ); } } } }