i want you to help me with this one I'm develepen a flutter app that scrape novels from a website the problem is the website shows the data in pages like page 1 have 8 novels if you want more you have to go to the page 2 and so on , now when create the function that scrape novels add the parametar int page to load the data from page 1 then page 2 and so on , NovelCubit(
serverLocator(),
serverLocator(),
serverLocator(),
serverLocator(),
serverLocator(),
serverLocator(),
serverLocator(),
serverLocator(),
)..getHotNovels(1),
child: const HomeScreen(), you see the issue here that I want to load the data in page 1 then change it to 2 when the user scroll down or click in a specific button for more novels and 3 and so on how to make it work , import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:learning/Core/Services/services_locator.dart';
import 'package:learning/Core/Utils/size.dart';
import 'package:learning/Presentation/Controller/Novel/novel_cubit.dart';
import 'package:learning/Presentation/Controller/Search/search_cubit.dart';
class NovelRemoteDataSource extends BaseNovelRemoteDataSource {
@override
Future getCompletedNovels(int page) async {
// Get the total number of pages
final url = "AppContanse.completedNovelUrl?page=page";
final totalPages = await getTotalPages(url);
final response = await http.get(Uri.parse(url));
if (page > totalPages) {
return [];
}
if (response.statusCode == 200) {
final document = parse(response.body);
final novelEntries = document.querySelectorAll('div.row');
List novels = [];
for (var entry in novelEntries) {
try {
final imgDiv = entry.querySelector('div.col-xs-3');
final infoDiv = entry.querySelector('div.col-xs-7');
if (imgDiv != null && infoDiv != null) {
final imgTag = imgDiv.querySelector('img.cover.lazy');
final imgSrc =
imgTag?.attributes['data-src'] ?? "Image URL not found";
final parsedUri = Uri.parse(imgSrc);
final path = parsedUri.path;
final img = path.split('/').last;
// Extract the id by removing '.jpg'
final id = img.replaceAll('.jpg', '');
final novelLink = infoDiv.querySelector('h3.novel-title a');
final novelTitle = novelLink?.attributes['title'] ??
novelLink?.text.trim() ??
"Title not found";
final authorSpan = infoDiv.querySelector('span.author');
final author =
authorSpan?.nodes.last.text?.trim() ?? "Author not found";
novels.add(
NovelModel(
id: id, // Set the id here
author: author,
status: '',
genre: const [],
publishers: '',
yearOfPublishing: '',
description: '',
title: novelTitle,
chapters: const [],
image: img,
),
);
}
} catch (e) {
log("An error occurred while processing an entry: $e");
continue;
}
@override
Future getHotNovels(int page) async {
final url = "AppContanse.hotNovelUrl?page=page";
final totalPages = await getTotalPages(url);
final response = await http.get(Uri.parse(url));
if (page > totalPages) {
return [];
}
if (response.statusCode == 200) {
final document = parse(response.body);
final novelEntries = document.querySelectorAll('div.row');
List novels = [];
for (var entry in novelEntries) {
try {
final imgDiv = entry.querySelector('div.col-xs-3');
final infoDiv = entry.querySelector('div.col-xs-7');
if (imgDiv != null && infoDiv != null) {
final imgTag = imgDiv.querySelector('img.cover.lazy');
final imgSrc =
imgTag?.attributes['data-src'] ?? "Image URL not found";
final parsedUri = Uri.parse(imgSrc);
final path = parsedUri.path;
final img = path.split('/').last;
final id = img.replaceAll('.jpg', '');
final novelLink = infoDiv.querySelector('h3.novel-title a');
final novelTitle = novelLink?.attributes['title'] ??
novelLink?.text.trim() ??
"Title not found";
@override
Future getLatestReleaseNovels(int page) async {
final url = "AppContanse.latestReleaseNovelUrl?page=page";
final totalPages = await getTotalPages(url);
final response = await http.get(Uri.parse(url));
if (page > totalPages) {
return [];
}
if (response.statusCode == 200) {
final document = parse(response.body);
final novelEntries = document.querySelectorAll('div.row');
List novels = [];
for (var entry in novelEntries) {
try {
final imgDiv = entry.querySelector('div.col-xs-3');
final infoDiv = entry.querySelector('div.col-xs-7');
if (imgDiv != null && infoDiv != null) {
final imgTag = imgDiv.querySelector('img.cover.lazy');
final imgSrc =
imgTag?.attributes['data-src'] ?? "Image URL not found";
final parsedUri = Uri.parse(imgSrc);
final path = parsedUri.path;
final img = path.split('/').last;
final id = img.replaceAll('.jpg', '');
final novelLink = infoDiv.querySelector('h3.novel-title a');
final novelTitle = novelLink?.attributes['title'] ??
novelLink?.text.trim() ??
"Title not found";
@override
Future getMostPopularNovels(int page) async {
final url = "AppContanse.popularNovelUrl?page=page";
final totalPages = await getTotalPages(url);
final response = await http.get(Uri.parse(url));
if (page > totalPages) {
return [];
}
if (response.statusCode == 200) {
final document = parse(response.body);
final novelEntries = document.querySelectorAll('div.row');
List novels = [];
for (var entry in novelEntries) {
try {
final imgDiv = entry.querySelector('div.col-xs-3');
final infoDiv = entry.querySelector('div.col-xs-7');
if (imgDiv != null && infoDiv != null) {
final imgTag = imgDiv.querySelector('img.cover.lazy');
final imgSrc =
imgTag?.attributes['data-src'] ?? "Image URL not found";
final parsedUri = Uri.parse(imgSrc);
final path = parsedUri.path;
final img = path.split('/').last;
final id = img.replaceAll('.jpg', '');
final novelLink = infoDiv.querySelector('h3.novel-title a');
final novelTitle = novelLink?.attributes['title'] ??
novelLink?.text.trim() ??
"Title not found";
if (response.statusCode == 200) {
var document = parse(response.body);
var novelEntries = document.querySelectorAll('div.row');
List novels = [];
for (var entry in novelEntries) {
try {
var titleElement = entry.querySelector('h3.novel-title');
var title = titleElement?.text.trim();
var imgElement = entry.querySelector('img.cover');
var image = imgElement?.attributes['src']?.split('/').last;
var authorElement = entry.querySelector('span.author');
var author = authorElement?.text.trim();
if (title != null && image != null && author != null) {
novels.add(NovelModel(
id: '', // Add an appropriate id if available
title: title,
author: author,
image: image,
genre: const [], // Add genres if you can extract them
status: '', // Add status if available
publishers: '', // Add publishers if available
yearOfPublishing: '', // Add year if available
description: '', // Add description if needed
chapters: const [], // Chapters can be added after scraping the details page
));
}
} catch (e) {
log('Error occurred while processing entry: $e');
continue;
}
}
return novels;
} else {
throw Exception(
'Failed to retrieve the webpage. Status code: ${response.statusCode}');
}
}
// Extract Chapter Title and Number
var chapterTitleElement = document.querySelector('a.chr-title span');
if (chapterTitleElement != null) {
var chapterTitleFull = chapterTitleElement.text.trim();
if (chapterTitleFull.contains(':')) {
var parts = chapterTitleFull.split(':');
chapterNumber = parts[0].replaceAll('Chapter', '').trim();
chapterTitle = parts[1].trim();
} else {
chapterTitle = chapterTitleFull; // Use full title if no ':' found
}
}
return ChapterContentModel(
chapterContent: chapterContent,
chapterNumber: chapterNumber,
chapterTitle: chapterTitle,
novelTitle: novelTitle,
); // Use chapterTitle instead of novelTitle
}
}
To solve your problem of loading more novel data from subsequent pages when the user scrolls down or clicks a specific button, you'll need to implement pagination in your Flutter application with the Bloc pattern. This involves updating your NovelCubit to handle loading additional pages and modifying your UI to trigger data fetching when needed.
Here's how you can achieve this:
1. Modify NovelCubit to Handle Pagination
Firstly, your NovelCubit needs to keep track of the current list of novels and the current page number. You'll also need to ensure that when you fetch new data, it gets appended to the existing list of novels, rather than replacing it.
Update your NovelCubit as follows:
class NovelCubit extends Cubit<NovelState> {
List<Novel> novels = [];
int currentPage = 1;
bool isFetching = false;
final NovelRepository novelRepository;
NovelCubit(this.novelRepository) : super(NovelLoading());
void getHotNovels(int page) async {
if (isFetching) return;
isFetching = true;
final currentState = state;
// Emit loading state based on whether it's the first page or subsequent pages
if (page == 1) {
emit(NovelLoading());
} else if (currentState is NovelSuccessfullyLoaded) {
emit(NovelSuccessfullyLoaded(
novels: currentState.novels,
isPaginationLoading: true,
hasReachedEnd: currentState.hasReachedEnd,
));
}
try {
final newNovels = await novelRepository.getHotNovels(page);
if (newNovels.isEmpty) {
// No more data available
emit(NovelSuccessfullyLoaded(
novels: novels,
isPaginationLoading: false,
hasReachedEnd: true,
));
} else {
if (page == 1) {
novels = newNovels;
} else {
novels.addAll(newNovels);
}
currentPage = page;
emit(NovelSuccessfullyLoaded(
novels: novels,
isPaginationLoading: false,
hasReachedEnd: false,
));
}
} catch (e) {
emit(NovelError(errorMessage: e.toString()));
}
isFetching = false;
}
}
2. Update Your States to Support Pagination
You'll need to adjust your NovelState to include information about pagination, such as whether more data is loading and if all data has been fetched.
Modify your NovelState and its subclasses:
abstract class NovelState {}
class NovelLoading extends NovelState {}
class NovelSuccessfullyLoaded extends NovelState {
final List<Novel> novels;
final bool isPaginationLoading;
final bool hasReachedEnd;
NovelSuccessfullyLoaded({
required this.novels,
this.isPaginationLoading = false,
this.hasReachedEnd = false,
});
}
class NovelError extends NovelState {
final String errorMessage;
NovelError({required this.errorMessage});
}
3. Update Your UI to Trigger Data Fetching
In your UI, you need to detect when the user has reached the end of the current list of novels and then fetch more data by incrementing the page number.
Modify your CarouselSlider in the HomeScreen:
BlocBuilder<NovelCubit, NovelState>(
builder: (context, novelState) {
if (novelState is NovelLoading) {
return Center(child: CircularProgressIndicator());
} else if (novelState is NovelSuccessfullyLoaded) {
return Column(
children: [
CarouselSlider.builder(
itemCount: novelState.novels.length,
itemBuilder: (context, index, realIndex) {
final novel = novelState.novels[index];
return Column(
// your novel item UI here
);
},
options: CarouselOptions(
// your existing options
onPageChanged: (index, reason) {
if (index == novelState.novels.length - 1 && !novelState.hasReachedEnd) {
var cubit = BlocProvider.of<NovelCubit>(context);
cubit.getHotNovels(cubit.currentPage + 1);
}
},
),
),
if (novelState.isPaginationLoading)
Center(child: CircularProgressIndicator()),
if (novelState.hasReachedEnd)
Center(child: Text('No more data')),
],
);
} else if (novelState is NovelError) {
return Center(child: Text(novelState.errorMessage));
}
return SizedBox.shrink();
},
),
Explanation:
Detecting End of List: In the CarouselOptions, we use the onPageChanged callback to detect when the user scrolls to the last item in the CarouselSlider. If the last item is reached and there's more data to load (!novelState.hasReachedEnd), we call getHotNovels with the next page number.
Handling Multiple Fetches: We use an isFetching flag in the NovelCubit to prevent multiple simultaneous fetches.
Updating the UI: We show a CircularProgressIndicator when more data is being loaded (novelState.isPaginationLoading) and a message when all data has been fetched (novelState.hasReachedEnd).
4. Ensure That Data Is Accumulated
By appending the new novels to the existing list in the NovelCubit, the novels displayed in the CarouselSlider will grow as more data is fetched. This way, your UI will display the combined list of novels from all loaded pages.
5. Handle Edge Cases and Errors
No More Data: When there are no more pages to load, getHotNovels will set hasReachedEnd to true, and the UI will display a message indicating that all data has been loaded.
Error Handling: Ensure that any errors during data fetching are properly caught and displayed to the user through the NovelError state.
6. Optional: Adjust for User Interaction
If you prefer the user to manually load more data, you can add a "Load More" button at the end of your list:
if (!novelState.hasReachedEnd)
ElevatedButton(
onPressed: () {
var cubit = BlocProvider.of<NovelCubit>(context);
cubit.getHotNovels(cubit.currentPage + 1);
},
child: Text('Load More'),
),
7. Example of Full Implementation
Here's a simplified version of how your HomeScreen and NovelCubit could look:
By adjusting your NovelCubit to handle pagination and updating your UI to trigger data fetching when the user scrolls to the end, you can effectively load additional pages of novels in your Flutter app. This approach ensures that your application scales well and provides a seamless experience for the user.
Remember to handle edge cases, such as when there's no more data to load or when errors occur during data fetching, to ensure robustness in your application.