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<List> 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<NovelModel> 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;
}
}
return novels;
} else {
throw Exception('Failed to load novels');
}
}
@override
Future<List> 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<NovelModel> 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";
final authorSpan = infoDiv.querySelector('span.author');
final author =
authorSpan?.nodes.last.text?.trim() ?? "Author not found";
novels.add(
NovelModel(
author: author,
status: '',
genre: const [],
publishers: '',
yearOfPublishing: '',
description: '',
title: novelTitle,
chapters: const [],
image: img,
id: id,
),
);
}
} catch (e) {
log("An error occurred while processing an entry: $e");
continue;
}
}
return novels;
} else {
throw Exception('Failed to load page');
}
}
@override
Future<List> 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<NovelModel> 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";
final authorSpan = infoDiv.querySelector('span.author');
final author =
authorSpan?.nodes.last.text?.trim() ?? "Author not found";
novels.add(
NovelModel(
author: author,
status: '',
genre: const [],
publishers: '',
yearOfPublishing: '',
description: '',
title: novelTitle,
chapters: const [],
image: img,
id: id,
),
);
}
} catch (e) {
log("An error occurred while processing an entry: $e");
continue;
}
}
return novels;
} else {
throw Exception('Failed to load page');
}
}
@override
Future<List> 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<NovelModel> 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";
final authorSpan = infoDiv.querySelector('span.author');
final author =
authorSpan?.nodes.last.text?.trim() ?? "Author not found";
novels.add(
NovelModel(
author: author,
status: '',
genre: const [],
publishers: '',
yearOfPublishing: '',
description: '',
title: novelTitle,
chapters: const [],
image: img,
id: id,
),
);
}
} catch (e) {
log("An error occurred while processing an entry: $e");
continue;
}
}
return novels;
} else {
throw Exception('Failed to load page');
}
}
@override
Future getNovelsDetails(String id) async {
final String url = "https://novelbin.me/novel-book/$id";
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final document = parse(response.body);
String safeExtract(dom.Element? element, {String? attribute}) {
if (element == null) return 'N/A';
if (attribute != null) return element.attributes[attribute] ?? 'N/A';
return element.text.trim();
}
final title =
safeExtract(document.querySelector('h3.title[itemprop="name"]'));
final authorMeta = document
.querySelector('span[itemprop="author"] meta[itemprop="name"]');
final author = safeExtract(authorMeta, attribute: 'content');
final genres = document.querySelectorAll('li').where((li) {
return li.querySelector('h3')?.text.trim() == 'Genre:';
}).expand((li) {
return li
.querySelectorAll(
'a[href^="https://novelbin.me/novelbin-genres/"]')
.map((a) => a.text.trim());
}).toList();
final statusElement = document
.querySelector('a[href^="https://novelbin.me/sort/novelbin-"]');
final status = safeExtract(statusElement);
final imageMeta = document.querySelector('meta[itemprop="image"]');
final imageUrl = safeExtract(imageMeta, attribute: 'content');
final img = imageUrl.split('/').last;
String description = 'N/A';
final descriptionDiv = document.querySelector('div#tab-description');
if (descriptionDiv != null) {
final descTextDiv = descriptionDiv.querySelector('div.desc-text');
if (descTextDiv != null) {
description = descTextDiv.text.trim();
}
}
final chapterList = await fetchChaptersList(id);
// Now return the extracted data in a NovelModel instance
return NovelModel(
title: title,
author: author,
genre: genres,
status: status,
image: img,
description: description,
publishers: '',
yearOfPublishing: '',
chapters: chapterList,
id: id,
);
} else {
throw Exception("Failed to load novel information");
}
} catch (e) {
// Optionally log or rethrow the error for debugging
log('Error occurred: $e');
throw Exception('Error occurred while fetching novel details');
}
if (response.statusCode == 200) {
var document = parse(response.body);
var novelEntries = document.querySelectorAll('div.row');
List<NovelModel> 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}');
}
dom.Document document = parse(pageContent);
// Extract Novel Title
final novelTitle =
document.querySelector('a.novel-title')?.text.trim() ?? 'Unknown Novel';
// Initialize chapter variables
String chapterNumber = 'Unknown Number';
String chapterTitle = 'Unknown Title';
String chapterContent = 'No Content Found.';
// 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
}
}
// Extract Chapter Content
var chapterContentElements = document.querySelector('#chr-content');
if (chapterContentElements != null) {
chapterContent = chapterContentElements
.getElementsByTagName('p')
.map((para) => para.text.trim())
.where((text) => text.isNotEmpty)
.join('\n\n');
}
return ChapterContentModel(
chapterContent: chapterContent,
chapterNumber: chapterNumber,
chapterTitle: chapterTitle,
novelTitle: novelTitle,
); // Use chapterTitle instead of novelTitle
}
}
It looks like you're trying to implement pagination in your Flutter app, where you load more novels from the website as the user scrolls down or presses a button. I'll guide you through how to modify your code to achieve this functionality.
Overview of the Solution:
Modify your NovelCubit:
Keep track of the current page number.
Provide a method to load more novels (i.e., fetch the next page).
Update the state to include the list of novels and loading status.
Update your UI (HomeScreen):
Detect when the user wants to load more data (either by scrolling or pressing a button).
Trigger the loadMoreNovels method in the NovelCubit.
Update the UI to reflect the new data.
Handle State Changes:
Ensure that the UI rebuilds when new novels are added.
Handle loading states to prevent duplicate requests.
Step 1: Modify the NovelCubit
First, let's modify your NovelCubit to manage pagination.
NovelCubit.dart
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:learning/Data/model/novel_model.dart';
import 'package:learning/Data/remote_data_source/novel_remote_data_source.dart';
class NovelCubit extends Cubit<NovelState> {
final NovelRemoteDataSource remoteDataSource;
List<NovelModel> novels = [];
int currentPage = 1;
bool isLoading = false;
bool hasMoreData = true; // Assuming the website has finite pages
NovelCubit(this.remoteDataSource) : super(NovelInitial());
void getHotNovels() {
// Load the first page
currentPage = 1;
novels.clear();
hasMoreData = true;
_fetchNovels();
}
void loadMoreNovels() {
if (isLoading || !hasMoreData) return;
currentPage++;
_fetchNovels();
}
void _fetchNovels() async {
try {
isLoading = true;
emit(NovelLoading());
final newNovels = await remoteDataSource.getHotNovels(currentPage);
if (newNovels.isNotEmpty) {
novels.addAll(newNovels);
emit(NovelSuccessfullyLoaded(List.from(novels))); // Emitting a new list
} else {
hasMoreData = false;
}
isLoading = false;
} catch (e) {
isLoading = false;
emit(NovelError(e.toString()));
}
}
}
// Novel States
abstract class NovelState {}
class NovelInitial extends NovelState {}
class NovelLoading extends NovelState {}
class NovelSuccessfullyLoaded extends NovelState {
final List<NovelModel> novels;
NovelSuccessfullyLoaded(this.novels);
}
class NovelError extends NovelState {
final String errorMessage;
NovelError(this.errorMessage);
}
hasMoreData: Determines if more data is available.
Methods:
getHotNovels(): Initializes the fetching process.
loadMoreNovels(): Fetches the next page.
_fetchNovels(): Internal method to fetch novels from the remote data source.
Step 2: Update the HomeScreen
Now, we'll update your HomeScreen to trigger loadMoreNovels when the user scrolls to the end.
Given that the CarouselSlider might not be ideal for infinite scrolling, it's better to use a ListView.builder or GridView.builder. Here's how you can modify your HomeScreen:
HomeScreen.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:learning/Presentation/Controller/Novel/novel_cubit.dart';
// Other imports...
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
// Your decoration code...
child: SafeArea(
child: BlocBuilder<NovelCubit, NovelState>(
builder: (context, novelState) {
if (novelState is NovelLoading && novelState.novels.isEmpty) {
// Show a loading indicator when the app is first started
return Center(child: CircularProgressIndicator());
} else if (novelState is NovelSuccessfullyLoaded) {
return NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification scrollInfo) {
if (!context.read<NovelCubit>().isLoading &&
scrollInfo.metrics.pixels ==
scrollInfo.metrics.maxScrollExtent) {
// Load more novels when scrolled to the bottom
context.read<NovelCubit>().loadMoreNovels();
}
return false;
},
child: ListView.builder(
itemCount: novelState.novels.length +
1, // Add 1 for the loading indicator
itemBuilder: (context, index) {
if (index == novelState.novels.length) {
// Show loading indicator at the bottom
return context.read<NovelCubit>().hasMoreData
? Center(child: CircularProgressIndicator())
: SizedBox(); // Empty space if no more data
}
final novel = novelState.novels[index];
return Column(
children: [
imageSlider(novel),
novelTitle(novel, context),
authorName(novel, context),
const SizedBox(
height: 5,
),
buttonReadNow(context, novel.id),
],
);
},
),
);
} else if (novelState is NovelError) {
return Center(
child: Text(novelState.errorMessage),
);
}
return SizedBox.shrink();
},
),
),
),
);
}
// Rest of your methods (imageSlider, novelTitle, authorName, buttonReadNow)
}
Explanation:
Replaced CarouselSlider with ListView.builder to handle infinite scrolling more effectively.
Used NotificationListener<ScrollNotification> to detect when the user has scrolled to the bottom of the list.
When the bottom is reached, loadMoreNovels is called.
A loading indicator is shown at the bottom while more novels are being fetched.
Note: If you prefer to keep using CarouselSlider, you can still detect the end using the onPageChanged callback, but using a ListView is more standard for infinite scrolling.
Step 3: Modify the MainScreen
Update your MainScreen to initialize the NovelCubit without passing the page number.
MainScreen.dart
// ... Your imports
class MainScreenContent extends StatelessWidget {
const MainScreenContent({super.key});
@override
Widget build(BuildContext context) {
return BlocConsumer<NavigationCubit, NavigationState>(
// ... Your code
);
}
Widget _buildBody(int currentIndex) {
List<Widget> navigationScreens = [
BlocProvider(
create: (context) => NovelCubit(serverLocator())
..getHotNovels(), // Remove the page parameter
child: const HomeScreen(),
),
// ... Rest of your screens
];
return IndexedStack(
index: currentIndex,
children: navigationScreens,
);
}
// Rest of your methods (_buildBottomNavigationBar, etc.)
}
Step 4: Handle State Changes Properly
Ensure your NovelState includes the list of novels, even during loading, so that the UI doesn't rebuild with an empty list.
Modify your NovelLoading state to include the current list of novels.
NovelCubit.dart (State classes)
class NovelLoading extends NovelState {
final List<NovelModel> novels;
NovelLoading(this.novels);
}
Modify your emit calls:
void _fetchNovels() async {
try {
isLoading = true;
emit(NovelLoading(List.from(novels))); // Pass the current novels
final newNovels = await remoteDataSource.getHotNovels(currentPage);
if (newNovels.isNotEmpty) {
novels.addAll(newNovels);
emit(NovelSuccessfullyLoaded(List.from(novels))); // Emitting a new list
} else {
hasMoreData = false;
}
isLoading = false;
} catch (e) {
isLoading = false;
emit(NovelError(e.toString()));
}
}
Alternate Approach: Using a "Load More" Button
If you prefer to have a "Load More" button instead of infinite scrolling, you can modify your HomeScreen like this:
HomeScreen.dart
// ... your imports
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
// ... your Scaffold and other code
return Scaffold(
body: Container(
// ... decoration
child: SafeArea(
child: BlocBuilder<NovelCubit, NovelState>(
builder: (context, novelState) {
// ... handle loading and error states
if (novelState is NovelSuccessfullyLoaded) {
return Column(
children: [
Expanded(
child: ListView.builder(
itemCount: novelState.novels.length,
itemBuilder: (context, index) {
final novel = novelState.novels[index];
return Column(
children: [
imageSlider(novel),
novelTitle(novel, context),
authorName(novel, context),
const SizedBox(
height: 5,
),
buttonReadNow(context, novel.id),
],
);
},
),
),
context.read<NovelCubit>().hasMoreData
? ElevatedButton(
onPressed: () {
context.read<NovelCubit>().loadMoreNovels();
},
child: Text('Load More'),
)
: SizedBox(),
],
);
}
return SizedBox.shrink();
},
),
),
),
);
}
// Rest of your methods
}
Explanation:
Added a "Load More" button at the bottom of the screen.
When pressed, it triggers loadMoreNovels to fetch the next page.
Additional Notes
Avoid Duplicate Requests: Ensure that isLoading is set appropriately to prevent multiple simultaneous requests.
Managing State: Always emit new instances of your state classes to trigger UI rebuilds.
Error Handling: Consider showing error messages in the UI if fetching data fails.
Testing: Test your implementation thoroughly to ensure it works as expected.
Conclusion
By modifying your NovelCubit to handle pagination and updating your HomeScreen to detect when more data needs to be loaded, you can implement the desired functionality. Whether you choose infinite scrolling or a "Load More" button depends on your preference and the user experience you want to provide.
Let me know if you have any questions or need further assistance!