community_bloc.dart 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import 'package:eye_video/bizmodule/main/community/blocs/community_event.dart';
  2. import 'package:eye_video/bizmodule/main/community/blocs/community_state.dart';
  3. import 'package:eye_video/bizmodule/main/community/model/community_model.dart';
  4. import 'package:eye_video/bizmodule/main/community/respositories/community_repository.dart';
  5. import 'package:eye_video/bizmodule/main/community/extension/ext_community.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter_bloc/flutter_bloc.dart';
  8. class CommunityBloc extends Bloc<CommunityEvent, CommunityState> {
  9. final CommunityRepository communityRepository;
  10. List<Community> mCommunityList = [];
  11. String nextPageUrl;
  12. CommunityBloc({@required this.communityRepository}) : super(null){
  13. add(EventRequest(isFirst: true, isRefresh: true));
  14. }
  15. @override
  16. Stream<CommunityState> mapEventToState(CommunityEvent event) async* {
  17. if (event is EventRequest) {
  18. if (event.isFirst) {
  19. yield StateRequestLoading();
  20. }
  21. try {
  22. if (event.isRefresh) {
  23. //刷新
  24. mCommunityList.clear();
  25. var communityModel = await communityRepository.fetchCommunity();
  26. nextPageUrl = communityModel.nextPageUrl ?? "";
  27. mCommunityList.addAll(communityModel.communityList);
  28. } else {
  29. //加载更多
  30. if (_hasNextPage(nextPageUrl)) {
  31. var communityModel = await communityRepository.fetchCommunity();
  32. nextPageUrl = communityModel.nextPageUrl ?? "";
  33. mCommunityList.addAll(communityModel.communityList.where((element) => !element.isHorizontalScrollCard));
  34. }
  35. }
  36. if (mCommunityList.isEmpty) {
  37. yield StateRequestEmpty();
  38. } else {
  39. yield StateRequestSuccess(List.of(mCommunityList), _hasNextPage(nextPageUrl));
  40. }
  41. } catch (e) {
  42. yield StateRequestFailure();
  43. }
  44. }
  45. }
  46. bool _hasNextPage(String nextPageUrl) {
  47. if (nextPageUrl == null || nextPageUrl.isEmpty) {
  48. return false;
  49. }
  50. try {
  51. Uri uri = Uri.parse(nextPageUrl);
  52. // ignore: unrelated_type_equality_checks
  53. if (uri.queryParameters['smallCardLast'] == null && uri.queryParameters['smallCardLast'] == 0 &&
  54. uri.queryParameters['pageCount'] == '0') {
  55. return false;
  56. }
  57. } catch (e) {
  58. return false;
  59. }
  60. return true;
  61. }
  62. }