0

Apreciaria mucho su ayuda. Estoy codificando mi primera aplicación en flutter. Hasta ahora estoy llamando a un script PHP en un servidor, que lee una base de datos MySql, este programa me devuelve un json que recibo perfectamente. Sin embargo, necesito mostrar en pantalla una lista con la información recolectada de la base de datos. Esta info es meteorológica y debo mostrarla en pantalla del móvil. Estoy completamente perdido, agradecería mucho cualquier ayuda. A continuación indico mi código.

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        title: 'Lectura de estaciones',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Scaffold(
            appBar: AppBar(
                title: Text('Lectura de estaciones')
            ),
            body: new ListView(
                children: [
                  _buildItem('Primera Lectura'),
                  _buildItem('Segunda Lectura'),
                  _buildItem('Tercera Lectura'),
                  _buildItem('Cuarta Lectura')
                ]
            )
        )
    );
  }
}
Widget _buildItem(String textTitle) {
  return new ListTile(
    title: new Text(textTitle),
    subtitle: new Text('Second station'),
    onTap: (){
      print(textTitle);
    },
  );
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  @override
 Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        centerTitle: true,
      ),
    );
  }
  Future getData() async{
    var url = "http://10.0.2.2/appr3/selectapp.php";
    http.Response response = await http.get(url);
    if (response.statusCode == 200) {
      var jsonResponse = jsonDecode(response.body);
      print(jsonResponse.toString());
    } else {
      print('Request falla con status: ${response.statusCode}.');
    }
  }
  @override
 void initState() {
    getData();
  }
}

No se si voy bien o terriblemente mal, nunca he estado tan perdido. Necesito probar urgentemente que si se puede. Agradezco su ayuda

5
  • Cuál es el error?
    – Bicho
    el 16 jul. 2020 a las 21:15
  • El error está en que no estoy bien ubicado. No funciona y siento que estoy en ensayo y error. Necesito recomendaciones. Soy un auténtico novato y siento que no tengo gps el 16 jul. 2020 a las 21:51
  • Debo mostrar el contenido del json leído y no se como hacerlo. el 16 jul. 2020 a las 21:52
  • Con esta variable var jsonResponse puedes utilizar un foreach para que vayas leyendo todo el json key=>value
    – Bicho
    el 16 jul. 2020 a las 21:55
  • Mil gracias. Ya solucioné. Fué muy valiosa tu ayuda el 17 jul. 2020 a las 18:41

1 respuesta 1

0

Puedes hacer que tu función getData retorne el response, asegúrate de hacerla tipo future object y asíncrona, así:

Future<Object> getData() async {
print('GETTING DATA');
var url = "http://10.0.2.2/appr3/selectapp.php";

final response = await http.get("${url}");

return response;
}

Y en seguida puedes poner un FutureBuilder para ser llenado con los datos:

Future _futureData;

 @override


void initState() {
    super.initState();
    _futureData = getData();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _futureData, //PONES COMO FUTURE EL RESULTADO DE TU FUNCION
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            print('SNAPSHOT ERROR' + snapshot.error.toString());
            if (snapshot.error
                .toString()
                .contains('SocketException: Connection failed')) {
              return Text('Error: revisa tu conexión a internet');
            } else if (snapshot.error
                .toString()
                .contains('CustomTimeoutException')) {
              return Text(
                  'Error: el servidor no responde, por favor inténtalo de nuevo más tarde');
            } else if (snapshot.error
                .toString()
                .contains('Error: No route to host')) {
              return Text('Error: Servidor no encontrado');
            } else {
              return Text('Error inesperado');
            }
          }

          if (snapshot.hasData) {
            if (snapshot.data.statusCode != null) {
              int status = snapshot.data.statusCode;
              if (status == 201) {
                var jsondecoded = jsonDecode((snapshot.data.body)); //AQUI HACES EL 
     DECODED 
        /* AQUI SI EL STATUS ES 201 (PUEDES CAMBIAR SEGUN EL STATUS QUE RETORNA TU BACKEDN 
     PUEDE SER  200) RETORNAS UN WIDGET LLAMADO ItemList que reibe como parametro una 
      lista on tu response decodificado*/
                return ItemList(list: jsondecoded); 
              } 
          } else {
            print('no tiene datos el snapshot' + snapshot.toString());
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  CircularProgressIndicator(),
                  SizedBox(
                    height: 15,
                  ),
                  Text('Cargando datos'),
                ],
              ),
            );
          }
        });
  }
}

Por último aqui está el código para que te des idea de como quedaría el widget que vaz a retornar

class ItemList extends StatefulWidget {
  final List list;

  ItemList({this.list});

  @override
  _ItemListState createState() => _ItemListState();
}

class _ItemListState extends State<ItemList> {
  Consts _consts = Consts();
  List list;
  bool _isLoading;
  bool _isDone;

  @override
  void initState() {
    super.initState();
    list = widget.list; // aqui le das el valor a la lista con tu resuesta del backend
    _isLoading = false;
    _isDone = false;
  }

  String _responseToShow = '';
   @override
  Widget build(BuildContext context) {
    return _isLoading
        ? CircularProgressIndicator()
        : ListView.builder(
      itemCount: list == null ? 0 : list.length,
      itemBuilder: (context, i) {
        return Container(
          padding: const EdgeInsets.all(10.0),
          child: GestureDetector(
            child: Card(
              child: ListTile(
                title: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Wrap(
                      children: <Widget>[
                        Column(
                          children: <Widget>[
                            Container(
                              width:
                              MediaQuery.of(context).size.width / 1.4,
                              alignment: Alignment.center,
                              child: Wrap(
                                direction: Axis.vertical,
                                crossAxisAlignment:
                                WrapCrossAlignment.center,
                                    children: <Widget>[
                                  Wrap(
                                    crossAxisAlignment:
                                    WrapCrossAlignment.center,
                                    direction: Axis.vertical,
                                    children: <Widget>[
                                      Text(list[i]['el_nombre_de_tu_campo'],
                                          TitleStyle),
                                      CarTitle(list[i]['el_nombre_de_tu_campo2']),
                                    ],
                                  ),
                                  Text(list[i]['el_nombre_de_tu_campo3']),
                                  Text(list[i]['el_nombre_de_tu_campo4']),
                                  Text(
                                      list[i]['el_nombre_de_tu_campo4'],
                                ],
                              ),
                            )
                          ],
                        ),
                        
  }

Donde dice el nombre de tu campo le pones el nombre de tu clave de tu json, esto es relativo y depende de la estructura de tu json, es solo un ejemplo para que te des una idea.

En general lo que se hace es

  1. Crear una función asíncrona que retorne tu response.
  2. Crear un FutureBuilder que en caso de que tu estatus sea 201 en este caso también puede ser 200 retorne un widget que es un ListView que recibe la información del response y la guarda en una lista y con ella va llenando los diferentes campos.

Te dejo mas info aqui esta super claro https://flutter.dev/docs/cookbook/networking/fetch-data

Si tienes dudas pregunta.

2
  • 1
    Mil gracias. Voy a mejorar lo que hice con tus recomendaciones en este momento solo he podido mostrar parte del json. Con tus recomendaciones voy a poder alcanzar los objetivos. Gracias nuevamente el 17 jul. 2020 a las 18:47
  • Me alegra que te sirva de algo, si tienes dudas comenta el 17 jul. 2020 a las 20:04

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.