I have a problem when I scroll to load another page I want to keep the current data and…
- User
I have a problem when I scroll to load another page I want to keep the current data and load new one on top of it without reflesh the whole screen every time I scroller , import 'dart:developer';
import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:learning/App/Contanse/app_contanse.dart'; import 'package:learning/Core/Services/services_locator.dart'; import 'package:learning/Core/Utils/size.dart'; import 'package:learning/Domain/Entites/novel.dart'; import 'package:learning/Presentation/Controller/Novel/novel_cubit.dart'; import 'package:learning/Presentation/Resources/Fonts/style_manager.dart'; import 'package:skeletonizer/skeletonizer.dart';
import '../Resources/Colors/color_manger.dart';
import '../Resources/Strings/stings_manager.dart'; import '../Resources/Theme/theme_manager.dart'; import '../Resources/Values/values_manger.dart'; import 'detail_screen.dart';
class HomeScreen extends StatelessWidget { const HomeScreen({super.key});
@override Widget build(BuildContext context) { final containerHeight = SizeConfig.size.height * 0.5; // 50% of the screen height final containerWidth = SizeConfig.size.width * 0.95; // 95% of the screen widt final ScrollController scrollController = ScrollController();
return Scaffold( body: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: Theme.of(context).brightness == Brightness.light ? ColorManger.homePageGradiantLight : ColorManger.homePageGradiantDark, ), ), child: CustomScrollView( controller: scrollController, slivers: [ SliverToBoxAdapter( child: BlocBuilder<NovelCubit, NovelState>( builder: (context, novelState) { if (novelState is NovelLoading) { return Skeletonizer( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( height: SizeConfig.size.height * 0.30, width: SizeConfig.size.width * 0.45, decoration: BoxDecoration( color: Colors.grey[800], // Placeholder for image borderRadius: BorderRadius.circular( BorderRadiusManager.b16), ), ), Container( margin: const EdgeInsets.symmetric(vertical: 8), height: 20, width: SizeConfig.size.width * 0.6, color: Colors.grey[700], // Placeholder for title ), Container( height: 16, width: SizeConfig.size.width * 0.3, color: Colors.grey[700], // Placeholder for author ), const SizedBox(height: 5), Container( height: 40, width: SizeConfig.size.width * 0.3, decoration: BoxDecoration( color: Colors.grey[800], // Placeholder for button borderRadius: BorderRadius.circular( BorderRadiusManager.b19), ), ), ], ), ); } else if (novelState is NovelSuccessfullyLoaded) { return SafeArea( child: CarouselSlider.builder( itemCount: novelState.novels.length, itemBuilder: (context, index, realIndex) { final novel = novelState.novels[index]; return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ imageSlider(novel), novelTitle(novel, context), authorName(novel, context), const SizedBox( height: 5, ), buttomReadNow(context, novel.id), ], ); }, options: CarouselOptions( height: SizeConfig.size.height * 0.65, autoPlay: true, enlargeCenterPage: true, viewportFraction: 0.8, ), ), ); } else if (novelState is NovelError) { return Center( child: Text(novelState.errorMessage), ); } return const SizedBox.shrink(); }, ), ), SliverToBoxAdapter( child: BlocProvider( create: (_) => NovelCubit( serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), )..getGenres(), child: BlocBuilder<NovelCubit, NovelState>( builder: (context, genresState) { if (genresState is GenresLoading) { return Skeletonizer( child: Padding( padding: const EdgeInsets.only(top: PaddingManger.p24), child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ ...List.generate( 30, (_) { return Container( margin: const EdgeInsets.only( left: MarginManger.m8), height: SizeConfig.size.height * 0.0606, width: SizeConfig.size.width * 0.2778, decoration: BoxDecoration( border: Border.all(), borderRadius: BorderRadius.circular( BorderRadiusManager.b8), color: Colors.grey[900], )); }, ) ], ), ), ), ); } else if (genresState is GenresLoadedSuccessfully) { return Padding( padding: const EdgeInsets.only(top: PaddingManger.p24), child: SizedBox( height: SizeConfig.size.height * 0.069, width: double.infinity, child: GridView.builder( scrollDirection: Axis.horizontal, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 1, mainAxisExtent: SizeConfig.size.width * 0.25, crossAxisSpacing: 50, childAspectRatio: 1 / 2, ), itemCount: genresState.genres.length, itemBuilder: (context, index) => Container( margin: const EdgeInsets.only(left: MarginManger.m8), height: SizeConfig.size.height * 0.0606, width: SizeConfig.size.width * 0.2778, decoration: BoxDecoration( color: ColorManger.grenresConteinerColor, border: Border.all(), borderRadius: BorderRadius.circular(BorderRadiusManager.b8), ), child: Center( child: Text( style: getTitleMediumStyle( color: ColorManger.whiteColor), textAlign: TextAlign.center, genresState.genres[index], ), ), ), ), ), ); } return const SizedBox.shrink(); }), ), ), SliverToBoxAdapter( child: BlocProvider( create: (_) => NovelCubit( serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), )..getCompletedNovels(), child: BlocBuilder<NovelCubit, NovelState>( builder: (context, completeNovelState) { if (completeNovelState is NovelLoading) { return loadingIndicitor(containerHeight, containerWidth); } else if (completeNovelState is NovelSuccessfullyLoaded) { return successResult(containerHeight, containerWidth, completeNovelState, context); } else if (completeNovelState is NovelError) { return errorResult(completeNovelState); } return const SizedBox.shrink(); }), ), ), SliverToBoxAdapter( child: Container( height: containerHeight, width: containerWidth, decoration: const BoxDecoration(color: Colors.blue), ), ), ], ), ), );}
Container loadingIndicitor(double containerHeight, double containerWidth) { return Container( margin: const EdgeInsets.only(top: MarginManger.m24), decoration: BoxDecoration( color: Colors.black, border: Border.all(color: Colors.white), borderRadius: BorderRadius.circular(BorderRadiusManager.b10), ), height: containerHeight, width: containerWidth, child: const Center( child: CircularProgressIndicator(), ), ); }
Container errorResult(NovelError completeNovelState) { return Container( margin: const EdgeInsets.only(top: MarginManger.m24), decoration: BoxDecoration( color: Colors.black, border: Border.all(color: Colors.white), borderRadius: BorderRadius.circular(BorderRadiusManager.b10), ), height: SizeConfig.size.height * 0.3, width: SizeConfig.size.width * 0.6, child: Center( child: Text(completeNovelState.errorMessage), ), ); }
Column successResult(double containerHeight, double containerWidth, NovelSuccessfullyLoaded completeNovelState, context) { return Column( children: [ Container( height: containerHeight / 8, width: containerWidth, margin: const EdgeInsets.only(top: MarginManger.m24), decoration: BoxDecoration( color: Colors.black, border: Border( top: BorderSide(color: ColorManger.whiteColor), left: BorderSide(color: ColorManger.whiteColor), right: BorderSide(color: ColorManger.whiteColor), ), borderRadius: BorderRadius.circular(BorderRadiusManager.b10), ), child: const Center( child: Text( StingsManager.completedNovels, ), ), ), Container( decoration: BoxDecoration( color: Colors.black, border: Border( bottom: BorderSide(color: ColorManger.whiteColor), left: BorderSide(color: ColorManger.whiteColor), right: BorderSide(color: ColorManger.whiteColor), ), borderRadius: BorderRadius.circular(BorderRadiusManager.b10), ), height: containerHeight, width: containerWidth, child: SingleChildScrollView( child: SizedBox( height: containerHeight, width: containerWidth, child: NotificationListener( onNotification: (scrollInfo) { if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent && scrollInfo is ScrollEndNotification) {
BlocProvider.of<NovelCubit>(context).updatePage(); } return true; }, child: GridView.builder( physics: const AlwaysScrollableScrollPhysics(), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, crossAxisSpacing: 8, mainAxisSpacing: 5, childAspectRatio: 0.65, ), itemCount: completeNovelState.novels.length, itemBuilder: (context, index) { return Column( children: [ Flexible( child: SizedBox( height: containerHeight * 0.5, width: containerWidth / 4, child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => BlocProvider( create: (context) => NovelCubit( serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), )..getNovelsDetails( completeNovelState.novels[index].id), child: const DetailScreen(), ), ), ); }, child: Column( children: [ ClipRRect( borderRadius: BorderRadius.circular( BorderRadiusManager.b8), child: Image.network(AppContanse .baseImageUrl + completeNovelState.novels[index].image), ), Flexible( child: Text( completeNovelState.novels[index].title, maxLines: 2, style: getLabelSmallStyle( color: ColorManger.whiteColor), textAlign: TextAlign.center, ), ) ], ), ), ), ), ], ); }, ), ), ), ), ), ], );}
Text authorName(Novel novel, BuildContext context) { return Text( novel.author, style: getLabelLargeStyle( color: Theme.of(context).brightness == Brightness.light ? ColorManger.authorNamedColorlight : ColorManger.authorNamedColordark), ); }
ElevatedButton buttomReadNow(context, id) { return ElevatedButton( style: buttonStyle(), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => BlocProvider( create: (context) => NovelCubit( serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), serverLocator(), )..getNovelsDetails(id), child: const DetailScreen(), ), ), ); }, child: Text( StingsManager.readNow, style: getLabelLargeStyle( color: ColorManger.whiteColor, ), )); }
Flexible novelTitle(Novel novel, BuildContext context) { return Flexible( child: Text( novel.title, maxLines: 2, textAlign: TextAlign.center, style: getTitleLargeStyle( color: Theme.of(context).brightness == Brightness.light ? ColorManger.blackColor : ColorManger.whiteColor, ), ), ); }
ClipRRect imageSlider(Novel novel) { return ClipRRect( borderRadius: BorderRadius.circular(BorderRadiusManager.b16), child: Container( height: SizeConfig.size.height * 0.40, width: SizeConfig.size.width * 0.45, decoration: const BoxDecoration(), child: image(AppContanse.baseImageUrl + novel.image), ), ); } }
Widget image(String url) { return Image.network( url, fit: BoxFit.fitHeight, ); } , import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:learning/Domain/Entites/novel.dart';
import 'package:learning/Domain/Usecase/get_completed_novels_usecase.dart'; import 'package:learning/Domain/Usecase/get_genres_usecase.dart';
import 'package:learning/Domain/Usecase/get_latest_release_novels_usecase.dart'; import 'package:learning/Domain/Usecase/get_most_popular_novels_usecase.dart'; import 'package:learning/Domain/Usecase/get_novels_details_usecase.dart'; import 'package:learning/Domain/Usecase/get_searched_novels_usecase.dart';
import '../../../Domain/Entites/chapter_content.dart'; import '../../../Domain/Usecase/get_chapter_content_usecase.dart'; import '../../../Domain/Usecase/get_hot_novels_usecase.dart';
part 'novel_state.dart';
class NovelCubit extends Cubit { final GetCompletedNovelsUsecase getCompletedNovelsUsecase; final GetChapterContentUsecase getChapterContentUsecase; final GetGenresUsecase getGenresUsecase; final GetHotNovelsUsecase getHotNovelsUsecase; final GetMostPopularNovelsUsecase getMostPopularNovelsUsecase; final GetLatestReleaseNovelsUsecase getLatestReleaseNovelsUsecase; final GetSearchedNovelsUsecase searchedNovelsUsecase; final GetNovelsDetailsUsecase getNovelsDetailsUsecase; int _currentPageNumber = 1; List currentNovels = []; NovelCubit( this.getChapterContentUsecase, this.getCompletedNovelsUsecase, this.getGenresUsecase, this.getHotNovelsUsecase, this.getMostPopularNovelsUsecase, this.getLatestReleaseNovelsUsecase, this.searchedNovelsUsecase, this.getNovelsDetailsUsecase, ) : super( NovelLoading(), );
Future getCompletedNovels() async { emit(NovelLoading());
final getCompletedNovelsUsecaseResult = await getCompletedNovelsUsecase.execute(_currentPageNumber); getCompletedNovelsUsecaseResult.fold( (error) => emit( NovelError( errorMessage: error.errorMessageError, ), ), (success) => emit( NovelSuccessfullyLoaded( success, ), ), );}
Future updatePage() async { _currentPageNumber++;
await getCompletedNovels();}
Future getHotNovels(int page) async { emit(NovelLoading()); final getHotNovelsUsecaseResult = await getHotNovelsUsecase.execute(page); getHotNovelsUsecaseResult.fold( (error) => emit( NovelError( errorMessage: error.errorMessageError, ), ), (success) => emit( NovelSuccessfullyLoaded( success, ), ), ); }
Future getNovelsDetails(String id) async { emit(NovelLoading()); final getNovelsDetailsUsecaseResult = await getNovelsDetailsUsecase.execute(id); getNovelsDetailsUsecaseResult.fold( (error) => emit( NovelError( errorMessage: error.errorMessageError, ), ), (success) => emit( NovelDaitelsLoaded( success, ), ), ); }
Future getChapterContent(String href) async { emit(ChapterContentLoading()); final getChapterContentUsecaseResult = await getChapterContentUsecase.execute(href); getChapterContentUsecaseResult.fold( (error) => emit( ChapterContentError( errorMessage: error.errorMessageError, ), ), (success) => emit( ChapterContentSuccessfullyLoaded( chapterContent: success, ), ), ); }
Future getSearchedNovels(String query, int page) async { emit(NovelLoading()); final getSearchedNovelsUsecaseResult = await searchedNovelsUsecase.execute(query, page); getSearchedNovelsUsecaseResult.fold( (error) => emit(NovelError(errorMessage: error.errorMessageError)), (success) => emit( NovelSuccessfullyLoaded(success), ), ); }
void reverseChapters() { final novel = (state as NovelDaitelsLoaded).novel; final reversedNovel = novel.copyWith( chapters: novel.chapters.reversed.toList(), ); emit(NovelDaitelsLoaded(reversedNovel)); }
Future getGenres() async { emit(GenresLoading()); final getGenresUsecaseResult = await getGenresUsecase.execute(); getGenresUsecaseResult.fold( (error) => emit( GenresError( errorMessage: error.errorMessageError, ), ), (success) => emit( GenresLoadedSuccessfully(success), ), ); } }
- Assistant
It looks like you're trying to implement infinite scrolling in your Flutter app using Bloc, but you're facing an issue where the entire screen refreshes, and you lose the existing data each time you scroll to load more. This happens because when you emit a loading state (
NovelLoading), your UI rebuilds and replaces the current data with the new one, rather than appending it.Here's how you can fix this issue:
-
Maintain the Existing Data: Instead of replacing the existing list of novels every time new data is fetched, you need to append the new novels to your existing list. This means you should maintain a list of all the novels that have been loaded so far.
-
Modify the State Management: You'll need to adjust your
NovelStateto hold the accumulated list of novels and include a loading status flag. This allows you to manage the loading state without replacing the existing data. -
Avoid Emitting Full Loading States on Pagination: When you're loading more data, instead of emitting a full loading state (which would rebuild the entire UI), you can emit a state that indicates loading more data, or simply update a loading flag within the current state.
Let's go through how you can implement these changes step by step.
1. Update Your Novel State
Create a state that holds the list of novels along with a loading indicator for pagination. This way, you can keep the existing novels and control the loading state during pagination.
// novel_state.dart part of 'novel_cubit.dart'; class NovelState extends Equatable { final List<Novel> novels; final bool isLoading; final bool isLoadingMore; final String errorMessage; const NovelState({ this.novels = const [], this.isLoading = false, this.isLoadingMore = false, this.errorMessage = '', }); NovelState copyWith({ List<Novel>? novels, bool? isLoading, bool? isLoadingMore, String? errorMessage, }) { return NovelState( novels: novels ?? this.novels, isLoading: isLoading ?? this.isLoading, isLoadingMore: isLoadingMore ?? this.isLoadingMore, errorMessage: errorMessage ?? this.errorMessage, ); } @override List<Object> get props => [novels, isLoading, isLoadingMore, errorMessage]; }2. Modify Your NovelCubit
Adjust your
NovelCubitto manage the list of novels and handle pagination correctly. Use thecopyWithmethod to update the state without losing the existing data.class NovelCubit extends Cubit<NovelState> { final GetCompletedNovelsUsecase getCompletedNovelsUsecase; // ... other dependencies int _currentPageNumber = 1; NovelCubit( this.getCompletedNovelsUsecase, // ... other dependencies ) : super(const NovelState()); Future<void> getCompletedNovels({bool isInitialLoad = false}) async { if (isInitialLoad) { emit(state.copyWith(isLoading: true, novels: [], errorMessage: '')); _currentPageNumber = 1; } else { emit(state.copyWith(isLoadingMore: true)); } final result = await getCompletedNovelsUsecase.execute(_currentPageNumber); result.fold( (error) => emit(state.copyWith( isLoading: false, isLoadingMore: false, errorMessage: error.errorMessageError, )), (novels) { _currentPageNumber++; final updatedNovels = List<Novel>.from(state.novels)..addAll(novels); emit(state.copyWith( novels: updatedNovels, isLoading: false, isLoadingMore: false, )); }, ); } void loadMoreCompletedNovels() { getCompletedNovels(isInitialLoad: false); } }Notes:
-
Initial Load vs. Pagination: When
isInitialLoadistrue, you're fetching the first page, so you clear the existing novels and reset the page number. For subsequent loads (pagination), you setisLoadingMoretotruewithout clearing the existing novels. -
Managing Page Number: Increment
_currentPageNumberonly after a successful fetch. This ensures that you don't skip pages if a request fails. -
Preserving Novels: Use
state.novelsto append new novels to the existing list.
3. Adjust Your UI to Handle the Updated State
Modify your
BlocBuilderin the UI to use the new state structure. Display a loading indicator appropriately without rebuilding the entire screen.BlocBuilder<NovelCubit, NovelState>( builder: (context, state) { if (state.isLoading && state.novels.isEmpty) { // Show initial loading indicator return Center(child: CircularProgressIndicator()); } else if (state.errorMessage.isNotEmpty && state.novels.isEmpty) { // Show error message return Center(child: Text(state.errorMessage)); } else { // Display the list of novels return NotificationListener<ScrollNotification>( onNotification: (scrollInfo) { if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent && !state.isLoadingMore && state.errorMessage.isEmpty) { context.read<NovelCubit>().loadMoreCompletedNovels(); } return false; }, child: GridView.builder( // Adjust the height and other properties as necessary itemCount: state.novels.length + (state.isLoadingMore ? 1 : 0), itemBuilder: (context, index) { if (index < state.novels.length) { final novel = state.novels[index]; // Build your novel item return NovelItem(novel: novel); } else { // Show the pagination loading indicator at the end return Center(child: CircularProgressIndicator()); } }, ), ); } }, );Notes:
-
Pagination Loading Indicator: When
state.isLoadingMoreistrue, we add an extra item at the end of the grid to show a loading indicator. -
Prevent Multiple Calls: Ensure that
loadMoreCompletedNovels()is called only when not already loading more data and no error exists.
4. Prevent UI Rebuilds on Pagination
Since we're now controlling the loading states more granularly, the UI won't refresh entirely when loading more data. we're only updating the parts of the UI that need to display new data or loading indicators.
5. Handle Errors Appropriately
Make sure to display errors without disrupting the user experience.
- If an error occurs during pagination, you might want to show a
SnackBaror a small message at the bottom, allowing the user to retry. - If the initial load fails, you can display a full-screen error message.
6. Initialize Data Correctly
Make sure you initiate the data load in the appropriate place. For example, you might want to load the initial data when the widget is first built.
@override void initState() { super.initState(); context.read<NovelCubit>().getCompletedNovels(isInitialLoad: true); }Note: If you're using
BlocProviderwithin the widget tree, you need to create your cubit at a point whereinitStateis accessible, such as within aStatefulWidget.7. Complete Example for the GridView Section
Here's how you might adjust the GridView section in your
HomeScreen:// Inside your successResult method Widget successResult(BuildContext context, NovelState state) { final containerHeight = SizeConfig.size.height * 0.5; final containerWidth = SizeConfig.size.width * 0.95; return Column( children: [ Container( // ... your existing container for title ), Container( // ... your existing container settings child: NotificationListener<ScrollNotification>( onNotification: (scrollInfo) { if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent && !state.isLoadingMore && state.errorMessage.isEmpty) { context.read<NovelCubit>().loadMoreCompletedNovels(); } return false; }, child: GridView.builder( // Adjust the height and other properties as necessary itemCount: state.novels.length + (state.isLoadingMore ? 1 : 0), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, // ... other properties ), itemBuilder: (context, index) { if (index < state.novels.length) { final novel = state.novels[index]; return Column( children: [ Flexible( child: SizedBox( // ... your existing code for individual novel items ), ), ], ); } else { // Show loading indicator at the bottom return Center( child: CircularProgressIndicator(), ); } }, ), ), ), ], ); }8. Ensure Consistent State Across the App
Since you're using multiple
BlocProviderinstances ofNovelCubit, make sure that theNovelCubithandling pagination is the same instance used to manage the state for your completed novels list. Otherwise, you'll end up with separate instances that don't share state.Consider providing the
NovelCubitat a higher level in your widget tree, so it's accessible where needed.void main() { runApp( BlocProvider( create: (context) => NovelCubit(getCompletedNovelsUsecase), child: MyApp(), ), ); }
By following these steps, your app should now load more data when the user scrolls to the bottom of the list without refreshing the entire screen or losing the existing data. The key is to manage your state in a way that maintains the accumulated data and to emit states that reflect only the changes needed for pagination.
Let me know if you have any questions or need further assistance with this implementation.
-