import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:skripsi_getit/data/model/movie.dart'; import 'package:skripsi_getit/data/state/movie_state.dart'; import 'package:skripsi_getit/services/repository/movie_repository.dart'; class PopularMovieCubit extends Cubit { final MovieRepository movieRepository; PopularMovieCubit(this.movieRepository) : super(MovieState()); int currentPage = 1; Future fetchPopularMovies() async { if (state.isLoading || !state.hasMoreData) return; emit(state.copyWith(isLoading: true)); try { final newMovies = await movieRepository.fetchPopularMovies( page: currentPage, ); final updatedMovies = List.from(state.movies) ..addAll(newMovies.results!); emit( state.copyWith( isLoading: false, movies: updatedMovies, hasMoreData: newMovies.results!.length >= 10, ), ); currentPage++; } catch (error) { emit(state.copyWith(isLoading: false, errorMessage: error.toString())); } } Future fetchWithForLoop(int count) async { for (int i = 0; i < count; i++) { await fetchPopularMovies(); } } Future fetchWithWhileLoop(int count) async { int i = 0; while (i < count) { await fetchPopularMovies(); i++; } } Future fetchWithDoWhileLoop(int count) async { int i = 0; do { await fetchPopularMovies(); i++; } while (i < count); } Future fetchPopularMoviesInBulk(int movieCount) async { final stopWatch = Stopwatch()..start(); currentPage = 1; // reset current page emit( MovieState(isLoading: true, movies: [], hasMoreData: true), ); // reset state try { List allMovies = []; int page = 1; while (allMovies.length < movieCount) { final movie = await movieRepository.fetchPopularMovies(page: page); if (movie.results == null || movie.results!.isEmpty) break; allMovies.addAll(movie.results!); page++; } emit( state.copyWith( isLoading: false, movies: allMovies.take(movieCount).toList(), hasMoreData: false, ), ); stopWatch.stop(); print( '${movieCount.toString()} completed in ${stopWatch.elapsed.inSeconds} seconds', ); } catch (e) { emit(state.copyWith(isLoading: false, errorMessage: e.toString())); } } void reset() { currentPage = 1; emit(MovieState()); } }