news_detail_provider.dart 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import 'package:flutter_riverpod/flutter_riverpod.dart';
  2. import 'package:news_app/constant/api_const.dart';
  3. import '../http/http_util.dart';
  4. import '../http/model_parser.dart';
  5. import '../model/news_detail_model.dart';
  6. import '../ui/me/user_favorite_page.dart';
  7. class NewsDetailProvider extends AutoDisposeNotifier<NewsDetailModel> {
  8. @override
  9. NewsDetailModel build() {
  10. return NewsDetailModel();
  11. }
  12. Future<void> fetchNewsDetail(String contentId) async {
  13. var jsonData = await HttpUtil().get(
  14. apiNewsDetail,
  15. //视频固定展示4个
  16. queryParameters: {"contentId": contentId},
  17. );
  18. final response = ModelParser.parseObject<NewsDetailModel>(
  19. jsonData,
  20. NewsDetailModel.fromJson,
  21. );
  22. state = response;
  23. }
  24. Future<void> fetchNewsShare({required String? contentId}) async {
  25. if (contentId == null || contentId.isEmpty) {
  26. return;
  27. }
  28. await HttpUtil().get(
  29. apiNewsShare,
  30. queryParameters: {"contentId": contentId},
  31. );
  32. }
  33. Future<void> fetchNewsLike({
  34. required String? contentId,
  35. required bool current,
  36. }) async {
  37. if (contentId == null || contentId.isEmpty) {
  38. return;
  39. }
  40. final jsonData = await HttpUtil().get(
  41. current ? apiNewsCancelLike : apiNewsLike,
  42. queryParameters: {"contentId": contentId},
  43. );
  44. if (jsonData == true) {
  45. if (current) {
  46. state = state.copyWith(
  47. likeCount: (state.likeCount ?? 1) - 1, //默认1是为了防止出现负数
  48. isLiked: false,
  49. );
  50. } else {
  51. //修改成功后,把 likeCount+1
  52. state = state.copyWith(
  53. likeCount: (state.likeCount ?? 0) + 1,
  54. isLiked: true,
  55. );
  56. }
  57. }
  58. }
  59. Future<void> fetchNewsFavorite({
  60. required String? contentId,
  61. required bool current,
  62. }) async {
  63. if (contentId == null || contentId.isEmpty) {
  64. return;
  65. }
  66. final jsonData = await HttpUtil().get(
  67. current ? apiNewsCancelFavorite : apiNewsFavorite,
  68. queryParameters: {"contentId": contentId},
  69. );
  70. if (jsonData == true) {
  71. //修改成功后,把favoriteCount+1
  72. if (current) {
  73. //修改成功后,把favoriteCount-1
  74. state = state.copyWith(
  75. favoriteCount: (state.favoriteCount ?? 1) - 1, //默认1是为了防止出现负数
  76. isFavorite: false,
  77. );
  78. ref
  79. .read(favoriteNewsProvider.notifier)
  80. .removeItemByContentId(contentId);
  81. } else {
  82. state = state.copyWith(
  83. favoriteCount: (state.favoriteCount ?? 0) + 1,
  84. isFavorite: true,
  85. );
  86. }
  87. }
  88. }
  89. }