import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import…
- User
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:html/parser.dart' as parser; import 'package:cached_network_image/cached_network_image.dart'; import 'package:url_launcher/url_launcher.dart';
void main() { runApp(const MyApp()); }
class MyApp extends StatelessWidget { const MyApp({super.key});
@override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData.dark(useMaterial3: true).copyWith( colorScheme: ColorScheme.fromSeed( seedColor: Colors.blueAccent, brightness: Brightness.dark), scaffoldBackgroundColor: const Color(0xFF121212), cardColor: const Color(0xFF1E1E1E), ), home: const AnimeListScreen(), ); } }
class AnimeListScreen extends StatefulWidget { const AnimeListScreen({super.key});
@override AnimeListScreenState createState() => AnimeListScreenState(); }
class AnimeListScreenState extends State { final List<Map<String, String>> _animeList = []; bool _isLoading = true; bool _hasMore = true; int _currentPage = 1; final ScrollController _scrollController = ScrollController(); static const userAgent = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Mobile Safari/537.36';
@override void initState() { super.initState(); _fetchAnimeList(); _scrollController.addListener(() { if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) { _loadMore(); } }); }
Future _fetchAnimeList([int page = 1]) async { const baseUrl = 'https://www.okanime.xyz/espisode-list'; final url = 'page'; try { final response = await http.get(Uri.parse(url), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { final document = parser.parse(response.body); final animeElements = document.querySelectorAll('div.section-content.mt-3 > div > div'); if (animeElements.isEmpty) { _hasMore = false; } else { final newAnimeList = animeElements.map((element) { final titleElement = element.querySelector('div.anime-title > h4'); final episodeElement = element.querySelector('div.anime-title > h5'); final imgElement = element.querySelector('div.episode-image > img'); final urlElement = element.querySelector('div.episode-image > a'); return { 'title': titleElement?.text.trim() ?? 'No title found', 'episode': episodeElement?.text.trim() ?? 'No episode number found', 'imgUrl': imgElement?.attributes['src'] ?? '', 'pageUrl': urlElement?.attributes['href'] ?? '', }; }).toList(); setState(() { _animeList.addAll(newAnimeList); _isLoading = false; }); } } else { _handleError('Failed to load page page'); } } catch (e) { _handleError('Error fetching anime list: e'); } }
void _handleError(String message) { if (kDebugMode) { print(message); } setState(() { _isLoading = false; }); ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text(message))); }
void _loadMore() { if (!_isLoading && _hasMore) { setState(() { _isLoading = true; _currentPage++; }); _fetchAnimeList(_currentPage); } }
Future _fetchStreamUrl(String pageUrl) async { try { final response = await http.get(Uri.parse(pageUrl), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { var document = parser.parse(response.body); var streamLinks = document.querySelectorAll('#streamlinks > a'); for (var link in streamLinks) { if (link.text.contains('sendvid')) { var embedUrl = link.attributes['data-src'] ?? 'No stream URL found'; if (embedUrl != 'No stream URL found') { final embedResponse = await http.get(Uri.parse(embedUrl), headers: { 'User-Agent': userAgent, }); if (embedResponse.statusCode == 200) { var embedDocument = parser.parse(embedResponse.body); var videoElement = embedDocument.querySelector('video source'); return videoElement?.attributes['src'] ?? 'No .mp4 URL found'; } } } } } return 'No .mp4 URL found'; } catch (e) { if (kDebugMode) { print('Error fetching stream URL: $e'); } return 'No .mp4 URL found'; } }
void _launchVideoUrl(String mp4Url) async { if (mp4Url != 'No .mp4 URL found') { if (await canLaunchUrl(Uri.parse(mp4Url))) { await launchUrl( Uri.parse(mp4Url), mode: LaunchMode.externalApplication, ); } else { _handleError('Could not launch video URL'); } } else { _handleError('Could not fetch video URL'); } }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: _isLoading && _animeList.isEmpty ? const Center(child: CircularProgressIndicator()) : ListView.builder( controller: _scrollController, itemCount: _hasMore ? _animeList.length + 1 : _animeList.length, itemBuilder: (context, index) { if (index < _animeList.length) { final anime = _animeList[index]; return Card( clipBehavior: Clip.antiAlias, margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Stack( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ CachedNetworkImage( imageUrl: anime['imgUrl']!, width: 120, height: 160, fit: BoxFit.cover, placeholder: (context, url) => const SizedBox( width: 120, height: 160, child: Center( child: CircularProgressIndicator()), ), errorWidget: (context, url, error) => const Icon(Icons.error), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( anime['title']!, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold), ), Text('${anime['episode']}'), ], ), ), ], ), ), Positioned( bottom: 8, right: 8, child: ElevatedButton( onPressed: () async { final mp4Url = await _fetchStreamUrl(anime['pageUrl']!); _launchVideoUrl(mp4Url); }, child: const Text('Watch Now'), ), ), ], ), ); } else { return Padding( padding: const EdgeInsets.all(16.0), child: Center( child: _isLoading ? const CircularProgressIndicator() : const SizedBox(), ), ); } }, ), ); }
@override void dispose() { _scrollController.dispose(); super.dispose(); } } improve design ui
- Assistant
To improve the UI design of your Flutter application, consider implementing the following enhancements. These changes focus on making the application more visually appealing and user-friendly while maintaining functionality. Here's how you can adjust your code:
-
Enhance Text Styles: Use consistent and visually appealing text styles for your titles and descriptions.
-
Add a Gradient to Cards: Provide a nice visual effect to cards by overlaying a gradient.
-
Implement Smooth Transition Effects: Use
HeroorPageRouteBuilderfor transitions within cards and pages. -
Refine Button Styles: Use Rounded Rectangle Border buttons for better aesthetics.
-
Use Animated List: With the
AnimatedListwidget, your list becomes more dynamic as items are added or removed.
Here's a revised version with some of these optimizations:
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:html/parser.dart' as parser; import 'package:cached_network_image/cached_network_image.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData.dark(useMaterial3: true).copyWith( colorScheme: ColorScheme.fromSeed( seedColor: Colors.blueAccent, brightness: Brightness.dark), scaffoldBackgroundColor: const Color(0xFF121212), cardColor: const Color(0xFF1E1E1E), ), home: const AnimeListScreen(), ); } } class AnimeListScreen extends StatefulWidget { const AnimeListScreen({super.key}); @override AnimeListScreenState createState() => AnimeListScreenState(); } class AnimeListScreenState extends State<AnimeListScreen> { final List<Map<String, String>> _animeList = []; bool _isLoading = true; bool _hasMore = true; int _currentPage = 1; final ScrollController _scrollController = ScrollController(); static const userAgent = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Mobile Safari/537.36'; @override void initState() { super.initState(); _fetchAnimeList(); _scrollController.addListener(() { if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) { _loadMore(); } }); } Future<void> _fetchAnimeList([int page = 1]) async { const baseUrl = 'https://www.okanime.xyz/espisode-list'; final url = '$baseUrl?page=$page'; try { final response = await http.get(Uri.parse(url), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { final document = parser.parse(response.body); final animeElements = document.querySelectorAll('div.section-content.mt-3 > div > div'); if (animeElements.isEmpty) { _hasMore = false; } else { final newAnimeList = animeElements.map((element) { final titleElement = element.querySelector('div.anime-title > h4'); final episodeElement = element.querySelector('div.anime-title > h5'); final imgElement = element.querySelector('div.episode-image > img'); final urlElement = element.querySelector('div.episode-image > a'); return { 'title': titleElement?.text.trim() ?? 'No title found', 'episode': episodeElement?.text.trim() ?? 'No episode number found', 'imgUrl': imgElement?.attributes['src'] ?? '', 'pageUrl': urlElement?.attributes['href'] ?? '', }; }).toList(); setState(() { _animeList.addAll(newAnimeList); _isLoading = false; }); } } else { _handleError('Failed to load page $page'); } } catch (e) { _handleError('Error fetching anime list: $e'); } } void _handleError(String message) { if (kDebugMode) { print(message); } setState(() { _isLoading = false; }); ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text(message))); } void _loadMore() { if (!_isLoading && _hasMore) { setState(() { _isLoading = true; _currentPage++; }); _fetchAnimeList(_currentPage); } } Future<String> _fetchStreamUrl(String pageUrl) async { try { final response = await http.get(Uri.parse(pageUrl), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { var document = parser.parse(response.body); var streamLinks = document.querySelectorAll('#streamlinks > a'); for (var link in streamLinks) { if (link.text.contains('sendvid')) { var embedUrl = link.attributes['data-src'] ?? 'No stream URL found'; if (embedUrl != 'No stream URL found') { final embedResponse = await http.get(Uri.parse(embedUrl), headers: { 'User-Agent': userAgent, }); if (embedResponse.statusCode == 200) { var embedDocument = parser.parse(embedResponse.body); var videoElement = embedDocument.querySelector('video source'); return videoElement?.attributes['src'] ?? 'No .mp4 URL found'; } } } } } return 'No .mp4 URL found'; } catch (e) { if (kDebugMode) { print('Error fetching stream URL: $e'); } return 'No .mp4 URL found'; } } void _launchVideoUrl(String mp4Url) async { if (mp4Url != 'No .mp4 URL found') { if (await canLaunchUrl(Uri.parse(mp4Url))) { await launchUrl( Uri.parse(mp4Url), mode: LaunchMode.externalApplication, ); } else { _handleError('Could not launch video URL'); } } else { _handleError('Could not fetch video URL'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Anime List'), ), body: _isLoading && _animeList.isEmpty ? const Center(child: CircularProgressIndicator()) : ListView.builder( controller: _scrollController, itemCount: _hasMore ? _animeList.length + 1 : _animeList.length, itemBuilder: (context, index) { if (index < _animeList.length) { final anime = _animeList[index]; return Container( margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), gradient: const LinearGradient( colors: [Color(0xFF2E7D32), Color(0xFF1B5E20)], begin: Alignment.topLeft, end: Alignment.bottomRight, ), ), child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), clipBehavior: Clip.antiAlias, elevation: 2, margin: EdgeInsets.zero, child: Stack( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ ClipRRect( borderRadius: BorderRadius.circular(8.0), child: CachedNetworkImage( imageUrl: anime['imgUrl']!, width: 120, height: 160, fit: BoxFit.cover, placeholder: (context, url) => const SizedBox( width: 120, height: 160, child: Center( child: CircularProgressIndicator()), ), errorWidget: (context, url, error) => const Icon(Icons.error), ), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( anime['title']!, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), const SizedBox(height: 8), Text( '${anime['episode']}', style: const TextStyle( fontSize: 14, color: Colors.white70, ), ), ], ), ), ], ), ), Positioned( bottom: 8, right: 8, child: ElevatedButton( style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), ), ), onPressed: () async { final mp4Url = await _fetchStreamUrl(anime['pageUrl']!); _launchVideoUrl(mp4Url); }, child: const Text('Watch Now'), ), ), ], ), ), ); } else { return Padding( padding: const EdgeInsets.all(16.0), child: Center( child: _isLoading ? const CircularProgressIndicator() : const SizedBox(), ), ); } }, ), ); } @override void dispose() { _scrollController.dispose(); super.dispose(); } }Key Improvements:
- Gradient Background: Added a gradient to cards to give a stylish look.
- Card Shape: Rounded the card edges to improve aesthetics.
- Consistent Text Styles: Updated text style to enhance readability.
- Image Border Radius: Applied corner radius to images for consistency with card design.
- Button Style: Used a rounded rectangle button for a modern look.
- Animation: Consider using an animated list or hero widget for transitions for further improvements.
These enhancements will make your application more visually compelling and engaging to users.
-
- User
add search
- Assistant
Adding a search feature to your Flutter app will allow users to filter and find specific anime titles from the list. Here’s a guide to implement a search bar in your app:
- Add a TextEditingController: This will manage the search input.
- Modify the
AppBarto include aTextFieldfor search. - Filter the anime list based on the search query.
- Update the UI to display the filtered results.
Here's how you can integrate a search function into your app:
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:html/parser.dart' as parser; import 'package:cached_network_image/cached_network_image.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData.dark(useMaterial3: true).copyWith( colorScheme: ColorScheme.fromSeed( seedColor: Colors.blueAccent, brightness: Brightness.dark), scaffoldBackgroundColor: const Color(0xFF121212), cardColor: const Color(0xFF1E1E1E), ), home: const AnimeListScreen(), ); } } class AnimeListScreen extends StatefulWidget { const AnimeListScreen({super.key}); @override AnimeListScreenState createState() => AnimeListScreenState(); } class AnimeListScreenState extends State<AnimeListScreen> { final List<Map<String, String>> _animeList = []; final List<Map<String, String>> _filteredAnimeList = []; bool _isLoading = true; bool _hasMore = true; int _currentPage = 1; final ScrollController _scrollController = ScrollController(); final TextEditingController _searchController = TextEditingController(); static const userAgent = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Mobile Safari/537.36'; @override void initState() { super.initState(); _fetchAnimeList(); _scrollController.addListener(() { if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) { _loadMore(); } }); _searchController.addListener(() { _filterAnimeList(); }); } Future<void> _fetchAnimeList([int page = 1]) async { const baseUrl = 'https://www.okanime.xyz/espisode-list'; final url = '$baseUrl?page=$page'; try { final response = await http.get(Uri.parse(url), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { final document = parser.parse(response.body); final animeElements = document.querySelectorAll('div.section-content.mt-3 > div > div'); if (animeElements.isEmpty) { _hasMore = false; } else { final newAnimeList = animeElements.map((element) { final titleElement = element.querySelector('div.anime-title > h4'); final episodeElement = element.querySelector('div.anime-title > h5'); final imgElement = element.querySelector('div.episode-image > img'); final urlElement = element.querySelector('div.episode-image > a'); return { 'title': titleElement?.text.trim() ?? 'No title found', 'episode': episodeElement?.text.trim() ?? 'No episode number found', 'imgUrl': imgElement?.attributes['src'] ?? '', 'pageUrl': urlElement?.attributes['href'] ?? '', }; }).toList(); setState(() { _animeList.addAll(newAnimeList); _filteredAnimeList.addAll(newAnimeList); _isLoading = false; }); } } else { _handleError('Failed to load page $page'); } } catch (e) { _handleError('Error fetching anime list: $e'); } } void _handleError(String message) { if (kDebugMode) { print(message); } setState(() { _isLoading = false; }); ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text(message))); } void _loadMore() { if (!_isLoading && _hasMore) { setState(() { _isLoading = true; _currentPage++; }); _fetchAnimeList(_currentPage); } } void _filterAnimeList() { final query = _searchController.text.toLowerCase(); setState(() { _filteredAnimeList.clear(); if (query.isEmpty) { _filteredAnimeList.addAll(_animeList); } else { _filteredAnimeList.addAll(_animeList.where((anime) { final title = anime['title']!.toLowerCase(); return title.contains(query); }).toList()); } }); } Future<String> _fetchStreamUrl(String pageUrl) async { try { final response = await http.get(Uri.parse(pageUrl), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { var document = parser.parse(response.body); var streamLinks = document.querySelectorAll('#streamlinks > a'); for (var link in streamLinks) { if (link.text.contains('sendvid')) { var embedUrl = link.attributes['data-src'] ?? 'No stream URL found'; if (embedUrl != 'No stream URL found') { final embedResponse = await http.get(Uri.parse(embedUrl), headers: { 'User-Agent': userAgent, }); if (embedResponse.statusCode == 200) { var embedDocument = parser.parse(embedResponse.body); var videoElement = embedDocument.querySelector('video source'); return videoElement?.attributes['src'] ?? 'No .mp4 URL found'; } } } } } return 'No .mp4 URL found'; } catch (e) { if (kDebugMode) { print('Error fetching stream URL: $e'); } return 'No .mp4 URL found'; } } void _launchVideoUrl(String mp4Url) async { if (mp4Url != 'No .mp4 URL found') { if (await canLaunchUrl(Uri.parse(mp4Url))) { await launchUrl( Uri.parse(mp4Url), mode: LaunchMode.externalApplication, ); } else { _handleError('Could not launch video URL'); } } else { _handleError('Could not fetch video URL'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: TextField( controller: _searchController, decoration: const InputDecoration( hintText: 'Search Anime...', border: InputBorder.none, hintStyle: TextStyle(color: Colors.white70), ), style: const TextStyle(color: Colors.white), cursorColor: Colors.white, ), ), body: _isLoading && _animeList.isEmpty ? const Center(child: CircularProgressIndicator()) : ListView.builder( controller: _scrollController, itemCount: _hasMore ? _filteredAnimeList.length + 1 : _filteredAnimeList.length, itemBuilder: (context, index) { if (index < _filteredAnimeList.length) { final anime = _filteredAnimeList[index]; return Container( margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), gradient: const LinearGradient( colors: [Color(0xFF2E7D32), Color(0xFF1B5E20)], begin: Alignment.topLeft, end: Alignment.bottomRight, ), ), child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), clipBehavior: Clip.antiAlias, elevation: 2, margin: EdgeInsets.zero, child: Stack( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ ClipRRect( borderRadius: BorderRadius.circular(8.0), child: CachedNetworkImage( imageUrl: anime['imgUrl']!, width: 120, height: 160, fit: BoxFit.cover, placeholder: (context, url) => const SizedBox( width: 120, height: 160, child: Center( child: CircularProgressIndicator()), ), errorWidget: (context, url, error) => const Icon(Icons.error), ), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( anime['title']!, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), const SizedBox(height: 8), Text( '${anime['episode']}', style: const TextStyle( fontSize: 14, color: Colors.white70, ), ), ], ), ), ], ), ), Positioned( bottom: 8, right: 8, child: ElevatedButton( style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), ), ), onPressed: () async { final mp4Url = await _fetchStreamUrl(anime['pageUrl']!); _launchVideoUrl(mp4Url); }, child: const Text('Watch Now'), ), ), ], ), ), ); } else { return Padding( padding: const EdgeInsets.all(16.0), child: Center( child: _isLoading ? const CircularProgressIndicator() : const SizedBox(), ), ); } }, ), ); } @override void dispose() { _scrollController.dispose(); _searchController.dispose(); super.dispose(); } }Key Changes:
- TextEditingController: Added a controller to listen to and manage search query updates.
- Search Bar in AppBar: Replaced the title with a
TextFieldthat captures user input for searching. - Filtering Logic: Added logic to filter
_animeListbased on the search query, updating_filteredAnimeListwhich is used to render the UI. - Search Performance: Search queries are case-insensitive due to
.toLowerCase(), making search more user-friendly.
This enhancement to your app allows users to quickly find their desired anime from the list, providing a better user experience.
- User
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:html/parser.dart' as parser; import 'package:cached_network_image/cached_network_image.dart'; import 'package:url_launcher/url_launcher.dart';
void main() { runApp(const MyApp()); }
class MyApp extends StatelessWidget { const MyApp({super.key});
@override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData.dark(useMaterial3: true).copyWith( colorScheme: ColorScheme.fromSeed( seedColor: Colors.blueAccent, brightness: Brightness.dark), scaffoldBackgroundColor: const Color(0xFF121212), cardColor: const Color(0xFF1E1E1E), ), home: const AnimeListScreen(), ); } }
class AnimeListScreen extends StatefulWidget { const AnimeListScreen({super.key});
@override AnimeListScreenState createState() => AnimeListScreenState(); }
class AnimeListScreenState extends State { final List<Map<String, String>> _animeList = []; bool _isLoading = true; bool _hasMore = true; int _currentPage = 1; final ScrollController _scrollController = ScrollController(); static const userAgent = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Mobile Safari/537.36';
@override void initState() { super.initState(); _fetchAnimeList(); _scrollController.addListener(() { if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) { _loadMore(); } }); }
Future _fetchAnimeList([int page = 1]) async { const baseUrl = 'https://www.okanime.xyz/espisode-list'; final url = 'page'; try { final response = await http.get(Uri.parse(url), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { final document = parser.parse(response.body); final animeElements = document.querySelectorAll('div.section-content.mt-3 > div > div'); if (animeElements.isEmpty) { _hasMore = false; } else { final newAnimeList = animeElements.map((element) { final titleElement = element.querySelector('div.anime-title > h4'); final episodeElement = element.querySelector('div.anime-title > h5'); final imgElement = element.querySelector('div.episode-image > img'); final urlElement = element.querySelector('div.episode-image > a'); return { 'title': titleElement?.text.trim() ?? 'No title found', 'episode': episodeElement?.text.trim() ?? 'No episode number found', 'imgUrl': imgElement?.attributes['src'] ?? '', 'pageUrl': urlElement?.attributes['href'] ?? '', }; }).toList(); setState(() { _animeList.addAll(newAnimeList); _isLoading = false; }); } } else { _handleError('Failed to load page page'); } } catch (e) { _handleError('Error fetching anime list: e'); } }
void _handleError(String message) { if (kDebugMode) { print(message); } setState(() { _isLoading = false; }); ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text(message))); }
void _loadMore() { if (!_isLoading && _hasMore) { setState(() { _isLoading = true; _currentPage++; }); _fetchAnimeList(_currentPage); } }
Future _fetchStreamUrl(String pageUrl) async { try { final response = await http.get(Uri.parse(pageUrl), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { var document = parser.parse(response.body); var streamLinks = document.querySelectorAll('#streamlinks > a'); for (var link in streamLinks) { if (link.text.contains('sendvid')) { var embedUrl = link.attributes['data-src'] ?? 'No stream URL found'; if (embedUrl != 'No stream URL found') { final embedResponse = await http.get(Uri.parse(embedUrl), headers: { 'User-Agent': userAgent, }); if (embedResponse.statusCode == 200) { var embedDocument = parser.parse(embedResponse.body); var videoElement = embedDocument.querySelector('video source'); return videoElement?.attributes['src'] ?? 'No .mp4 URL found'; } } } } } return 'No .mp4 URL found'; } catch (e) { if (kDebugMode) { print('Error fetching stream URL: $e'); } return 'No .mp4 URL found'; } }
void _launchVideoUrl(String mp4Url) async { if (mp4Url != 'No .mp4 URL found') { if (await canLaunchUrl(Uri.parse(mp4Url))) { await launchUrl( Uri.parse(mp4Url), mode: LaunchMode.externalApplication, ); } else { _handleError('Could not launch video URL'); } } else { _handleError('Could not fetch video URL'); } }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Anime List'), ), body: _isLoading && _animeList.isEmpty ? const Center(child: CircularProgressIndicator()) : ListView.builder( controller: _scrollController, itemCount: _hasMore ? _animeList.length + 1 : _animeList.length, itemBuilder: (context, index) { if (index < _animeList.length) { final anime = _animeList[index]; return Container( margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), gradient: const LinearGradient( colors: [Color(0xFF2E7D32), Color(0xFF1B5E20)], begin: Alignment.topLeft, end: Alignment.bottomRight, ), ), child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), clipBehavior: Clip.antiAlias, elevation: 2, margin: EdgeInsets.zero, child: Stack( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ ClipRRect( borderRadius: BorderRadius.circular(8.0), child: CachedNetworkImage( imageUrl: anime['imgUrl']!, width: 120, height: 160, fit: BoxFit.cover, placeholder: (context, url) => const SizedBox( width: 120, height: 160, child: Center( child: CircularProgressIndicator()), ), errorWidget: (context, url, error) => const Icon(Icons.error), ), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( anime['title']!, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), const SizedBox(height: 8), Text( '${anime['episode']}', style: const TextStyle( fontSize: 14, color: Colors.white70, ), ), ], ), ), ], ), ), Positioned( bottom: 8, right: 8, child: ElevatedButton( style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), ), ), onPressed: () async { final mp4Url = await _fetchStreamUrl(anime['pageUrl']!); _launchVideoUrl(mp4Url); }, child: const Text('Watch Now'), ), ), ], ), ), ); } else { return Padding( padding: const EdgeInsets.all(16.0), child: Center( child: _isLoading ? const CircularProgressIndicator() : const SizedBox(), ), ); } }, ), ); }
@override void dispose() { _scrollController.dispose(); super.dispose(); } } optimize app speed
- Assistant
Optimizing the speed and performance of a Flutter app involves several strategies that focus on smoother UI experiences and efficient network calls. Below are some techniques to enhance your current app’s speed:
Optimization Strategies
-
Efficient Network Requests
- Use HTTP Client Pooling: Reuse HTTP clients for network requests to reduce resource usage.
- Limit Concurrent Requests: Avoid overwhelming resources or the API by limiting requests.
-
Caching and Image Optimization
- Enable HTTP Caching: Use
http_cachepackages to reduce repeated network fetches. - Upgrade Image Caching: If CachedNetworkImage isn't providing enough optimization, cache larger images manually.
- Enable HTTP Caching: Use
-
Efficient State Management
- Optimize State Updates: Only rebuild widgets when absolutely necessary. Consider using state management solutions like
Provider,Riverpod, orBloc. - Avoid Frequent State Changes: Reduce how often the UI rebuilds by decoupling heavy logic from
buildmethods.
- Optimize State Updates: Only rebuild widgets when absolutely necessary. Consider using state management solutions like
-
Improve ListView Performance
- Use ListView.builder Efficiently: Ensure
ListView.builderis only used for large datasets. - Add Keys to Lists: Provide unique
Keyvalues for list items if modifying a collection dynamically.
- Use ListView.builder Efficiently: Ensure
-
Asynchronous Initialization
- Use
FutureBuilderorStreamBuilder: Instead of handling network calls ininitState, use these widgets to keep logic decoupled from UI.
- Use
Here's an updated version of your code incorporating some of these optimizations:
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:html/parser.dart' as parser; import 'package:cached_network_image/cached_network_image.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData.dark(useMaterial3: true).copyWith( colorScheme: ColorScheme.fromSeed( seedColor: Colors.blueAccent, brightness: Brightness.dark, ), scaffoldBackgroundColor: const Color(0xFF121212), cardColor: const Color(0xFF1E1E1E), ), home: const AnimeListScreen(), ); } } class AnimeListScreen extends StatefulWidget { const AnimeListScreen({super.key}); @override AnimeListScreenState createState() => AnimeListScreenState(); } class AnimeListScreenState extends State<AnimeListScreen> { final List<Map<String, String>> _animeList = []; bool _isLoading = true; bool _hasMore = true; int _currentPage = 1; final ScrollController _scrollController = ScrollController(); final http.Client _client = http.Client(); static const userAgent = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Mobile Safari/537.36'; @override void initState() { super.initState(); _fetchAnimeList(); _scrollController.addListener(() { if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) { _loadMore(); } }); } Future<void> _fetchAnimeList([int page = 1]) async { const baseUrl = 'https://www.okanime.xyz/espisode-list'; final url = '$baseUrl?page=$page'; try { final response = await _client.get(Uri.parse(url), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { final document = parser.parse(response.body); final animeElements = document.querySelectorAll('div.section-content.mt-3 > div > div'); if (animeElements.isEmpty) { _hasMore = false; } else { final newAnimeList = animeElements.map((element) { final titleElement = element.querySelector('div.anime-title > h4'); final episodeElement = element.querySelector('div.anime-title > h5'); final imgElement = element.querySelector('div.episode-image > img'); final urlElement = element.querySelector('div.episode-image > a'); return { 'title': titleElement?.text.trim() ?? 'No title found', 'episode': episodeElement?.text.trim() ?? 'No episode number found', 'imgUrl': imgElement?.attributes['src'] ?? '', 'pageUrl': urlElement?.attributes['href'] ?? '', }; }).toList(); setState(() { _animeList.addAll(newAnimeList); _isLoading = false; }); } } else { _handleError('Failed to load page $page'); } } catch (e) { _handleError('Error fetching anime list: $e'); } } void _handleError(String message) { if (kDebugMode) { print(message); } setState(() { _isLoading = false; }); ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text(message))); } void _loadMore() { if (!_isLoading && _hasMore) { setState(() { _isLoading = true; _currentPage++; }); _fetchAnimeList(_currentPage); } } Future<String> _fetchStreamUrl(String pageUrl) async { try { final response = await _client.get(Uri.parse(pageUrl), headers: { 'User-Agent': userAgent, }); if (response.statusCode == 200) { var document = parser.parse(response.body); var streamLinks = document.querySelectorAll('#streamlinks > a'); for (var link in streamLinks) { if (link.text.contains('sendvid')) { var embedUrl = link.attributes['data-src'] ?? 'No stream URL found'; if (embedUrl != 'No stream URL found') { final embedResponse = await _client.get(Uri.parse(embedUrl), headers: { 'User-Agent': userAgent, }); if (embedResponse.statusCode == 200) { var embedDocument = parser.parse(embedResponse.body); var videoElement = embedDocument.querySelector('video source'); return videoElement?.attributes['src'] ?? 'No .mp4 URL found'; } } } } } return 'No .mp4 URL found'; } catch (e) { if (kDebugMode) { print('Error fetching stream URL: $e'); } return 'No .mp4 URL found'; } } void _launchVideoUrl(String mp4Url) async { if (mp4Url != 'No .mp4 URL found') { if (await canLaunchUrl(Uri.parse(mp4Url))) { await launchUrl( Uri.parse(mp4Url), mode: LaunchMode.externalApplication, ); } else { _handleError('Could not launch video URL'); } } else { _handleError('Could not fetch video URL'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Anime List'), ), body: _isLoading && _animeList.isEmpty ? const Center(child: CircularProgressIndicator()) : ListView.builder( controller: _scrollController, itemCount: _hasMore ? _animeList.length + 1 : _animeList.length, itemBuilder: (context, index) { if (index < _animeList.length) { final anime = _animeList[index]; return Container( margin: const EdgeInsets.symmetric( horizontal: 16, vertical: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), gradient: const LinearGradient( colors: [Color(0xFF2E7D32), Color(0xFF1B5E20)], begin: Alignment.topLeft, end: Alignment.bottomRight, ), ), child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), clipBehavior: Clip.antiAlias, elevation: 2, margin: EdgeInsets.zero, child: Stack( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ ClipRRect( borderRadius: BorderRadius.circular(8.0), child: CachedNetworkImage( imageUrl: anime['imgUrl']!, width: 120, height: 160, fit: BoxFit.cover, placeholder: (context, url) => const SizedBox( width: 120, height: 160, child: Center( child: CircularProgressIndicator()), ), errorWidget: (context, url, error) => const Icon(Icons.error), ), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( anime['title']!, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), const SizedBox(height: 8), Text( '${anime['episode']}', style: const TextStyle( fontSize: 14, color: Colors.white70, ), ), ], ), ), ], ), ), Positioned( bottom: 8, right: 8, child: ElevatedButton( style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), ), ), onPressed: () async { final mp4Url = await _fetchStreamUrl(anime['pageUrl']!); _launchVideoUrl(mp4Url); }, child: const Text('Watch Now'), ), ), ], ), ), ); } else { return Padding( padding: const EdgeInsets.all(16.0), child: Center( child: _isLoading ? const CircularProgressIndicator() : const SizedBox(), ), ); } }, ), ); } @override void dispose() { _scrollController.dispose(); _client.close(); super.dispose(); } }Key Changes:
- HTTP Client Reuse: Reuse a single
http.Clientinstance for all network requests to reduce overhead. - State Management: Kept state management principles simple, but ensure handling is efficient during screen updates.
- UI Rebuilds: Make sure layouts only rebuild when necessary, maintaining responsive UI experiences.
- Error Handling: Enhanced error handling functionality to continue loading silently where appropriate.
These improvements aim to streamline your app’s performance by doing less work and better utilizing resources. Adjust and test further as needed for your specific use case and platform requirements.
-