I want to implement  Infinite scrolling how to do it , 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<NovelState> {
  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<Novel> currentNovels = [];
  NovelCubit(
    this.getChapterContentUsecase,
    this.getCompletedNovelsUsecase,
    this.getGenresUsecase,
    this.getHotNovelsUsecase,
    this.getMostPopularNovelsUsecase,
    this.getLatestReleaseNovelsUsecase,
    this.searchedNovelsUsecase,
    this.getNovelsDetailsUsecase,
  ) : super(
          NovelLoading(),
        );

  Future<void> getCompletedNovels() async {
    emit(NovelLoading());

    final getCompletedNovelsUsecaseResult =
        await getCompletedNovelsUsecase.execute(_currentPageNumber);
    getCompletedNovelsUsecaseResult.fold(
        (error) => emit(
              NovelError(
                errorMessage: error.errorMessageError,
              ),
            ), (success) {
      currentNovels.addAll(success);
      emit(NovelSuccessfullyLoaded(currentNovels));
      emit(
        NovelSuccessfullyLoaded(
          currentNovels,
        ),
      );
    });
  }

  Future<void> updatePage() async {
    _currentPageNumber++;

    await getCompletedNovels();
  }

  Future<void> 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<void> 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<void> 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<void> 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<void> getGenres() async {
    emit(GenresLoading());
    final getGenresUsecaseResult = await getGenresUsecase.execute();
    getGenresUsecaseResult.fold(
      (error) => emit(
        GenresError(
          errorMessage: error.errorMessageError,
        ),
      ),
      (success) => emit(
        GenresLoadedSuccessfully(success),
      ),
    );
  }
} , 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<ScrollNotification>(
                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,
  );
}