Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

I want to add A CircularProgressIndicator at the bottom of the grid view when the state…

  1. User

    I want to add A CircularProgressIndicator at the bottom of the grid view when the state is NovelPaginationLoading but keep the previouse list as it is in the ui , 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({bool isLoadingPage = false}) async { if (isLoadingPage) { } else { emit(NovelLoading()); } final getCompletedNovelsUsecaseResult = await getCompletedNovelsUsecase.execute(currentPageNumber); getCompletedNovelsUsecaseResult.fold( (error) => emit( NovelError( errorMessage: error.errorMessageError, ), ), (success) { emit(NovelLoading()); currentNovels.addAll(success); emit(NovelSuccessfullyLoaded(currentNovels)); }); }

    Future updatePage() async { currentPageNumber++;

    await getCompletedNovels(isLoadingPage: true);
    

    }

    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), ), ); } } , // ignore_for_file: public_member_api_docs, sort_constructors_first part of 'novel_cubit.dart';

    sealed class NovelState extends Equatable { const NovelState();

    @override List get props => []; }

    final class NovelLoading extends NovelState {}

    final class NovelPaginationLoading extends NovelState {}

    final class NovelDaitelsLoaded extends NovelState { final Novel novel;

    const NovelDaitelsLoaded(this.novel); @override List get props => [novel]; }

    final class NovelSuccessfullyLoaded extends NovelState { final List novels;

    const NovelSuccessfullyLoaded(this.novels); @override List get props => [novels]; }

    final class NovelError extends NovelState { final String errorMessage;

    const NovelError({required this.errorMessage}); @override List get props => [errorMessage]; }

    class ChapterContentSuccessfullyLoaded extends NovelState { final ChapterContent chapterContent;

    const ChapterContentSuccessfullyLoaded({ required this.chapterContent, }); @override List get props => [chapterContent]; }

    class ChapterContentError extends NovelState { final String errorMessage;

    const ChapterContentError({required this.errorMessage}); @override List get props => [errorMessage]; }

    class ChapterContentLoading extends NovelState {}

    class GenresLoadedSuccessfully extends NovelState { final List genres;

    const GenresLoadedSuccessfully( this.genres, ); @override List get props => [genres]; }

    class GenresError extends NovelState { final String errorMessage;

    const GenresError({required this.errorMessage}); @override List get props => [errorMessage]; }

    class GenresLoading extends NovelState {} , 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(); // Listen for scroll events on controller scrollController.addListener(() { if (scrollController.position.pixels == scrollController.position.maxScrollExtent) { BlocProvider.of(context).updatePage(); } }); 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 buildSliderLoadingIndicator(); } 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), ), ), ], ), ), ); }

    Skeletonizer _buildSliderLoadingIndicator() { 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), ), ), ], ), ); }

    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 ScrollUpdateNotification) { BlocProvider.of(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, fit: BoxFit.cover, ), ), 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, ); }

  2. Assistant

    To display a CircularProgressIndicator at the bottom of your GridView during pagination loading—while keeping the existing list of items visible—you can modify your NovelSuccessfullyLoaded state to include an isPaginationLoading flag. This flag will indicate whether new data is being loaded due to pagination. Here's how you can achieve this:

    1. Modify the State Class: Update your NovelSuccessfullyLoaded state to include an isPaginationLoading boolean flag.

      final class NovelSuccessfullyLoaded extends NovelState {
        final List<Novel> novels;
        final bool isPaginationLoading;
      
        const NovelSuccessfullyLoaded(
          this.novels, {
          this.isPaginationLoading = false,
        });
      
        @override
        List<Object> get props => [novels, isPaginationLoading];
      }
      
    2. Update the Cubit: In your NovelCubit, when loading more data (pagination), you should:

      • Emit NovelSuccessfullyLoaded with isPaginationLoading: true before calling the use case to fetch more data.
      • After fetching the data, emit NovelSuccessfullyLoaded with isPaginationLoading: false.

      Update your getCompletedNovels method as follows:

      Future<void> getCompletedNovels({bool isLoadingPage = false}) async {
        if (isLoadingPage) {
          emit(NovelSuccessfullyLoaded(currentNovels, isPaginationLoading: true));
        } else {
          emit(NovelLoading());
        }
        final getCompletedNovelsUsecaseResult = await getCompletedNovelsUsecase.execute(currentPageNumber);
        getCompletedNovelsUsecaseResult.fold(
          (error) => emit(
            NovelError(
              errorMessage: error.errorMessageError,
            ),
          ),
          (success) {
            currentNovels.addAll(success);
            emit(NovelSuccessfullyLoaded(currentNovels, isPaginationLoading: false));
          },
        );
      }
      

      And in the updatePage method:

      Future<void> updatePage() async {
        currentPageNumber++;
        await getCompletedNovels(isLoadingPage: true);
      }
      
    3. Modify the UI: In your GridView.builder, adjust the itemCount to include an extra item when isPaginationLoading is true. Update the itemBuilder to display the CircularProgressIndicator when the index corresponds to this extra item.

      Here's how you can modify your successResult method:

      Column successResult(double containerHeight, double containerWidth,
          NovelSuccessfullyLoaded completeNovelState, BuildContext context) {
        return Column(
          children: [
            // ... your existing code for the header
            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: GridView.builder(
                    physics: const AlwaysScrollableScrollPhysics(),
                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      crossAxisSpacing: 8,
                      mainAxisSpacing: 5,
                      childAspectRatio: 0.65,
                    ),
                    itemCount: completeNovelState.novels.length +
                        (completeNovelState.isPaginationLoading ? 1 : 0),
                    itemBuilder: (context, index) {
                      if (index == completeNovelState.novels.length &&
                          completeNovelState.isPaginationLoading) {
                        return Center(child: CircularProgressIndicator());
                      } else {
                        final novel = completeNovelState.novels[index];
                        return Column(
                          children: [
                            Flexible(
                              child: SizedBox(
                                height: containerHeight * 0.5,
                                width: containerWidth / 4,
                                child: InkWell(
                                  onTap: () {
                                    // Navigate to details screen
                                  },
                                  child: Column(
                                    children: [
                                      ClipRRect(
                                        borderRadius: BorderRadius.circular(
                                            BorderRadiusManager.b8),
                                        child: Image.network(
                                          AppContanse.baseImageUrl + novel.image,
                                          fit: BoxFit.cover,
                                        ),
                                      ),
                                      Flexible(
                                        child: Text(
                                          novel.title,
                                          maxLines: 2,
                                          style: getLabelSmallStyle(
                                              color: ColorManger.whiteColor),
                                          textAlign: TextAlign.center,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ],
                        );
                      }
                    },
                  ),
                ),
              ),
            ),
          ],
        );
      }
      

      Explanation:

      • itemCount: Increased by 1 when isPaginationLoading is true to account for the loading indicator.
      • itemBuilder: Checks if the current index is the last one and isPaginationLoading is true. If so, it returns a CircularProgressIndicator; otherwise, it builds the grid item as usual.
    4. Triggering Pagination: Ensure that you have logic that triggers updatePage() when the user scrolls to the bottom of the GridView. You've already added a NotificationListener for ScrollNotification. Make sure it correctly detects when the user has scrolled to the end.

      onNotification: (scrollInfo) {
        if (scrollInfo.metrics.pixels ==
                scrollInfo.metrics.maxScrollExtent &&
            scrollInfo is ScrollUpdateNotification) {
          BlocProvider.of<NovelCubit>(context).updatePage();
        }
        return true;
      },
      
    5. Handle State Changes Appropriately: With these changes, your UI should respond to state changes by:

      • Displaying existing novels when NovelSuccessfullyLoaded is emitted.
      • Adding a loading indicator at the bottom when isPaginationLoading is true.

    Final Notes:

    • State Management: By including the loading flag in your state, you avoid unnecessary complex state transitions and keep your UI responsive.
    • UI Updates: The GridView adjusts dynamically based on the itemCount, and the loading indicator is seamlessly integrated at the bottom.
    • User Experience: This approach ensures that users see continuous content flow without abrupt changes, enhancing the overall experience.

    Here's the summary of changes you need to make:

    • Add isPaginationLoading to NovelSuccessfullyLoaded state.
    • Emit NovelSuccessfullyLoaded with isPaginationLoading: true before loading more data.
    • Emit NovelSuccessfullyLoaded with isPaginationLoading: false after data is loaded.
    • Adjust itemCount and itemBuilder in your GridView to account for the loading indicator.

    By following these steps, you'll effectively display a CircularProgressIndicator at the bottom of your GridView during pagination while keeping the previously loaded novels visible to the user.