todas las clases funcionales

This commit is contained in:
2024-05-16 16:13:59 +02:00
parent 0c1ef39a32
commit 5f4dc6fc01
6 changed files with 119 additions and 75 deletions

View File

@ -12,7 +12,7 @@ class NoticiasPage extends StatefulWidget {
}
class _NoticiasPageState extends State<NoticiasPage> {
Map<String, List<String>> noticiasPorTitulo = {};
Map<String, List<Future<String>>> noticiasPorTitulo = {};
@override
void initState() {
@ -24,47 +24,71 @@ class _NoticiasPageState extends State<NoticiasPage> {
final response = await http.get(Uri.parse('http://www.crcivan.com/escaparate/noticias.cgi?idpadre=92776&idempresa=31637'));
if (response.statusCode == 200) {
var document = htmlParser.parse(response.body);
var dataElements = document.querySelectorAll('html > body > div > center > table > tbody > tr > td > div > center > table > tbody > tr > td > table > tbody > tr > td > font');
var tituloElements = document.querySelectorAll('html > body > div > center > table > tbody > tr > td > div > center > table > tbody > tr > td > table > tbody > tr > td > b > a');
for (int i = 0; i < tituloElements.length; i++) {
String titulo = tituloElements[i].text.trim();
String noticia = dataElements[i].text.trim();
// Extrayendo el enlace href del elemento <a>
var linkElement = tituloElements[i];
String? link = linkElement.attributes['href'];
if (!noticiasPorTitulo.containsKey(titulo)) {
noticiasPorTitulo[titulo] = [];
if (link != null) {
noticiasPorTitulo[titulo] = [cargarContenidoUrl(link)];
}
noticiasPorTitulo[titulo]?.add(noticia);
}
// Esperar todas las promesas para que se resuelvan
await Future.wait(noticiasPorTitulo.values.expand((element) => element).toList());
setState(() {});
} else {
throw Exception('fallo al cargar noticias');
throw Exception('Fallo al cargar noticias');
}
}
//Función para desplegar noticias desde los contenedores
/*Future<void> obtenerDatosNoticias() async {
var linkElements = document.querySelectorAll('html > body > div > center > table > tbody > tr > td > div > center > table > tbody > tr > td > table > tbody > tr > td > a');
String? link = linkElements[i].attributes['href'];
if (response.statusCode == 200) {
for (int i = 0; i < tituloElements.length; i++) {
String titulo = tituloElements[i].text.trim();
String noticia = dataElements[i].text.trim();
Future<String> cargarContenidoUrl(String url) async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var document = htmlParser.parse(response.body);
var paragraphAndLists = document.querySelectorAll('html > body > div > center > table > tbody > tr > td > div > center > table > tbody > tr > td > table > tbody > tr > td > font > font > p, html > body > div > center > table > tbody > tr > td > div > center > table > tbody > tr > td > table > tbody > tr > td > font > font > ul');
String content = '';
String currentParagraphContent = '';
if (!noticiasPorTitulo.containsKey(titulo)) {
noticiasPorTitulo[titulo] = [];
for (var element in paragraphAndLists) {
if (element.localName == 'p') {
// Guardar el contenido del párrafo actual
if (currentParagraphContent.isNotEmpty) {
content += currentParagraphContent + '\n';
currentParagraphContent = '';
}
currentParagraphContent += element.text.trim() + '\n';
} else if (element.localName == 'ul') {
// Si hay un párrafo antes de la lista, agregarlo al contenido
if (currentParagraphContent.isNotEmpty) {
content += currentParagraphContent + '\n';
currentParagraphContent = '';
}
// Agregar la lista al contenido
var listItems = element.querySelectorAll('li');
for (var listItem in listItems) {
content += '- ${listItem.text.trim()}\n';
}
noticiasPorTitulo[titulo]?.add(noticia);
}
setState(() {});
} else {
throw Exception('fallo al cargar noticias');
}
}*/
// Agregar el último párrafo si no hay lista después
if (currentParagraphContent.isNotEmpty) {
content += currentParagraphContent + '\n';
}
return content;
} else {
throw Exception('Fallo al cargar contenido de URL: $url');
}
}
@override
Widget build(BuildContext context) {
@ -74,7 +98,7 @@ class _NoticiasPageState extends State<NoticiasPage> {
children: [
Positioned.fill(
child: Image(
image: AssetImage('assets/logo-fondo.png'),
image: AssetImage('assets/logo-fondo-verde.png'),
fit: BoxFit.cover,
),
),
@ -82,24 +106,40 @@ class _NoticiasPageState extends State<NoticiasPage> {
itemCount: noticiasPorTitulo.length,
itemBuilder: (context, index) {
String titulo = noticiasPorTitulo.keys.elementAt(index);
List<String>? noticias = noticiasPorTitulo[titulo];
List<Future<String>>? noticias = noticiasPorTitulo[titulo];
return ExpansionTile(
title: Text(
titulo,
style: TextStyle(fontWeight: FontWeight.bold),
),
children: noticias != null
? noticias.map((noticia) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
noticia,
style: TextStyle(fontSize: 16.0),
),
);
}).toList()
: [],
return FutureBuilder<List<String>>(
future: Future.wait(noticias ?? []),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (!snapshot.hasData) {
return Text('No hay datos');
} else {
return Container(
color: Colors.white.withOpacity(0.5), // Fondo blanco con 50% de opacidad
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
child: ExpansionTile(
title: Text(
titulo,
style: TextStyle(fontWeight: FontWeight.bold),
),
children: snapshot.data!.map((noticia) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
noticia,
style: TextStyle(fontSize: 16.0),
),
);
}).toList(),
),
);
}
},
);
},
),