topic_provider.dart 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import 'package:flutter_riverpod/flutter_riverpod.dart';
  2. import 'package:news_app/constant/api_const.dart';
  3. import 'package:news_app/http/http_util.dart';
  4. import 'package:news_app/model/topic_hot_model.dart';
  5. import 'package:news_app/model/topic_item_model.dart';
  6. import 'package:news_app/model/topic_rank_model.dart';
  7. import '../http/model_parser.dart';
  8. /// @author: bo.zeng
  9. /// @email: cnhbwds@gmail.com
  10. /// @date: 2025 2025/4/18 10:43
  11. /// @description:
  12. class TopicProvider extends Notifier<TopicData> {
  13. @override
  14. TopicData build() {
  15. return TopicData();
  16. }
  17. Future<void> fetchTopicHot() async {
  18. var jsonData = await HttpUtil().get(
  19. apiTopicHot,
  20. queryParameters: {"sid": "411683596922949"},
  21. );
  22. final newsList = ModelParser.parseList<TopicHotModel>(
  23. jsonData,
  24. TopicHotModel.fromJson,
  25. );
  26. //直接修改 state.topicHotList 不会触发状态更新。要确保通过 state = newState 来更新整个状态对象。
  27. state = state.copyWith(topicHotList: newsList);
  28. }
  29. Future<void> fetchRankHot() async {
  30. var jsonData = await HttpUtil().get(
  31. apiTopicRank,
  32. queryParameters: {"sid": "411683596922949", "pn": 0, "ps": 10},
  33. );
  34. final newsList = ModelParser.parseList<TopicRankModel>(
  35. jsonData,
  36. TopicRankModel.fromJson,
  37. );
  38. state = state.copyWith(topicRankList: newsList);
  39. }
  40. }
  41. class TopicData {
  42. final List<TopicHotModel> topicHotList;
  43. final List<TopicRankModel> topicRankList;
  44. TopicData({this.topicHotList = const [], this.topicRankList = const []});
  45. TopicData copyWith({
  46. List<TopicHotModel>? topicHotList,
  47. List<TopicRankModel>? topicRankList,
  48. TopicItemModel? topicItemModel,
  49. }) {
  50. return TopicData(
  51. topicHotList: topicHotList ?? this.topicHotList,
  52. topicRankList: topicRankList ?? this.topicRankList,
  53. );
  54. }
  55. }