Problem displaying a captured json from an API in my column widget - Flutter

Asked

Viewed 31 times

0

I have a problem I couldn’t solve, so I’m coming to you to give me a hand. I’m searching for a json from an API, the data search process goes well (I use a print() that shows me that if I got the data), the problem arises when I want to show this json data in my column widget (Column : [Text (), ...]) I’m working with null Safety (maybe this has to do with the problem, but I’m not sure, because in previous versions I did not have this problem)

This is the json I get:

[
    {
        "idCliente": "1",
        "ci": "1234567",
        "nombre": "jUAN",
        "apPaterno": "Perez",
        "apMaterno": "Fernandez",
        "correo": "[email protected]",
        "telefono": "7654321",
        "idUserss": "juan123",
        "imagenNueva": "https://thumbs.dreamstime.com/b/vector-el-icono-del-avatar-del-usuario-para-el-sitio-web-o-el-m%C3%B3vil-45837377.jpg",
        "imagenAnterior": "https://thumbs.dreamstime.com/b/vector-el-icono-del-avatar-del-usuario-para-el-sitio-web-o-el-m%C3%B3vil-45837377.jpg",
        "nombreImagenNueva": "https://thumbs.dreamstime.com/b/vector-el-icono-del-avatar-del-usuario-para-el-sitio-web-o-el-m%C3%B3vil-45837377.jpg",
        "directorio": "imagenes"
    }
]

This is the method responsible for bringing me the json:

Future<Perfil> listar() async {
  var url = 'https://midominio.com/data';
  var urlfull = Uri.parse(url);
  var response = await http.get(urlfull);

  if (response.statusCode == 200) {
    var result = response.body;
    var decoded = json.decode(result);
    print(decoded);
    var retornar = Perfil.fromJson(decoded);
    return retornar;
  } else {
    throw Exception('Fallo al cargar la lista');
  }
}

This is my model class for json:

class Perfil {
  String idCliente;
  String ci;
  String nombre;
  String apPaterno;
  String apMaterno;
  String correo;
  String telefono;
  String idUserss;
  String imagenNueva;
  String imagenAnterior;
  String nombreImagenNueva;
  String directorio;

  Perfil({
    required this.idCliente,
    required this.ci,
    required this.nombre,
    required this.apPaterno,
    required this.apMaterno,
    required this.correo,
    required this.telefono,
    required this.idUserss,
    required this.imagenNueva,
    required this.imagenAnterior,
    required this.nombreImagenNueva,
    required this.directorio,
  });

  factory Perfil.fromJson(Map<String, dynamic> json) => Perfil(
        idCliente: json["idCliente"] ?? json["idCliente"],
        ci: json["ci"] ?? json["ci"],
        nombre: json["nombre"] ?? json["nombre"],
        apPaterno: json["apPaterno"] ?? json["apPaterno"],
        apMaterno: json["apMaterno"] ?? json["apMaterno"],
        correo: json["correo"] ?? json["correo"],
        telefono: json["telefono"] ?? json["telefono"],
        idUserss: json["idUserss"] ?? json["idUserss"],
        imagenNueva: json["imagenNueva"] ?? json["imagenNueva"],
        imagenAnterior: json["imagenAnterior"] ?? json["imagenAnterior"],
        nombreImagenNueva:
            json["nombreImagenNueva"] ?? json["nombreImagenNueva"],
        directorio: json["directorio"] ?? json["directorio"],
      );

  Map<String, dynamic> toJson() => {
        "idCliente": idCliente,
        "ci": ci,
        "nombre": nombre,
        "apPaterno": apPaterno,
        "apMaterno": apMaterno,
        "correo": correo,
        "telefono": telefono,
        "idUserss": idUserss,
        "imagenNueva": imagenNueva,
        "imagenAnterior": imagenAnterior,
        "nombreImagenNueva": nombreImagenNueva,
        "directorio": directorio,
      };
}

And this is mine class where I show the API data in widgets but it tells me that the snapshot is without data, IE, it’s like I’m not bringing anything in json but actually if I get the data but it brings not visualize it.

class UserPerfil extends StatefulWidget {
  @override
  State createState() => _UserPerfilState();
}

class _UserPerfilState extends State<UserPerfil> {
  Future<Perfil>? listaPerfil;

  @override
  void initState() {
    super.initState();
    listaPerfil = listar();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Mi Perfil"),
      ),
      body: Container(
        color: Theme.of(context).backgroundColor,
        child: CustomPaint(
          painter: CurvaSesion(mcolor: Constants.global!),
          child: FutureBuilder<Perfil>(
              future: listaPerfil,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  if (snapshot.hasData) {
                    return Column(
                      children: [
                        Text(snapshot.data!.nombre),
                        Text(snapshot.data!.apPaterno),
                        Text(snapshot.data!.apMaterno),
                        Text(snapshot.data!.correo),
                      ],
                    );
                  } else if (snapshot.hasError) {
                    return Center(
                        child: Text(
                            "NO SE HA CARGADO LOS DATOS: ${snapshot.hasError}"));
                  }
                } else {
                  return Center(
                    child: CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(
                          Theme.of(context).buttonColor),
                    ),
                  );
                }
                return Container();
              }),
        ),
      ),
    );
  }
}

Please, if anyone could help me I would appreciate it, I am seriously considering going back to an older version because so far I have not been able to resolve this (suspecting that perhaps null Safety is to blame)

1 answer

1


You haven’t told us exactly what your problem is, but looking at your JSON, it’s possibly a problem with the way you treat it, change the following block to:

Future<Perfil> listar() async {
  var url = 'https://midominio.com/data';
  var urlfull = Uri.parse(url);
  var response = await http.get(urlfull);

  if (response.statusCode == 200) {
    var result = response.body;
    var decoded = json.decode(result);
    print(decoded);
    var retornar = Perfil.fromJson(decoded[0]);
    return retornar;
  } else {
    throw Exception('Fallo al cargar la lista');
  }
}

Explanation

The problem you are facing is due to the JSON returned from your API. You are returning an array of objects, which in turn when "Decode" is done on the flutter, is returning a List<dynamic>.

The problem is easily solved by taking the first item from the list to turn it into an object Profile.

var retornar = Perfil.fromJson(decoded[0]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.