Home > Blockchain >  Error trying to Populate a MAP in flutter using a JSON from C#
Error trying to Populate a MAP in flutter using a JSON from C#

Time:02-04

This is the API REST in C# to return a JSON

public async Task Leer([FromForm] string token) { try {

 string jsonResultado = await Clases.AccesoDatos.JsonData("SELECT * FROM vistatransacciones");             
           jsonResultado= jsonResultado.Substring(1);
           int longitud = jsonResultado.Length - 1;
           jsonResultado = jsonResultado.Substring(0,longitud);               
            string simple = "'";
            string dobleComilla = "\x022";
            string json = jsonResultado.Replace(simple,dobleComilla);                
            return Content( json,"application/json" );
        }
        catch (Exception ex)
        {

            return BadRequest(ex.Message);
        }
    }

This is the OUTPUT from de API REST {"idRegistro":"4","idUsuario":"1","FechaRegistro":"2023-01-25T00:00:00","FechaGasto":"2023-01-25T00:00:00","TipoGasto":"OTRO","TipoTransaccion":"otro","Descripcion":"test","Monto":"3222.00","Nombre":"XXXXX","Ruta":"C:\DocumentosGastoApp\coin_dollar_money.ico","Pagado":false,"nota":"Nada"}

This the MAP: {idRegistro: 4, idUsuario: 1, FechaRegistro: 2023-01-25T00:00:00, FechaGasto: 2023-01-25T00:00:00, TipoGasto: OTRO, TipoTransaccion: otro, Descripcion: test, Monto: 3222.00, Nombre: XXXX, Ruta: C:\DocumentosGastoApp\coin_dollar_money.ico, Pagado: false, nota: Nada}

This is the flutter code to read de JSON:

  final Map<String, dynamic> productsMap = json.decode(resp.body);
  productsMap.forEach((key, value) {
    final tempProduct = Product.fromMap(value);
    tempProduct.id = key;
    products.add(tempProduct);
  });

This is the flutter error msg:

_TypeError (type 'String' is not a subtype of type 'Map<String, dynamic>')

This is the model in flutter:

import 'dart:convert';

List<Product> productFromMap(String str) =>
    List<Product>.from(json.decode(str).map((x) => Product.fromMap(x)));

String productToMap(List<Product> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toMap())));

class Product {
  Product({
    this.idRegistro,
    this.idUsuario,
    this.fechaRegistro,
    this.fechaGasto,
    this.tipoGasto,
    this.tipoTransaccion,
    this.descripcion,
    required this.monto,
    this.nombre,
    this.ruta,
    required this.pagado,
    required this.nota,
    this.id,
  });

  bool pagado;
  String? idRegistro;
  String? idUsuario;
  String? descripcion;
  String? nombre;
  String? ruta;
  DateTime? fechaRegistro;
  DateTime? fechaGasto;
  String? tipoGasto;
  int monto;
  String? tipoTransaccion;
  String nota;
  String? id; //Esto es opcional pues el id no existe al momento de la creacion

  factory Product.fromJson(String str) => Product.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory Product.fromMap(Map<String, dynamic> json) => Product(
        idRegistro: json["idRegistro"],
        idUsuario: json["idUsuario"],
        fechaRegistro: DateTime.parse(json["FechaRegistro"]),
        fechaGasto: DateTime.parse(json["FechaGasto"]),
        tipoGasto: json["TipoGasto"],
        tipoTransaccion: json["TipoTransaccion"],
        descripcion: json["Descripcion"],
        monto: json["monto"],
        nombre: json["Nombre"],
        ruta: json["ruta"],
        pagado: json["pagado"],
        nota: json["nota"],
        id: json["idRegistro"],
        //picture: json["picture"],
      );

  Map<String, dynamic> toMap() => {
        "idRegistro": idRegistro,
        "idUsuario": idUsuario,
        "FechaRegistro": fechaRegistro,
        "FechaGasto": fechaGasto,
        "TipoGasto": tipoGasto,
        "TipoTransaccion": tipoTransaccion,
        "Descripcion": descripcion,
        "Monto": monto,
        "Nombre": nombre,
        "ruta": ruta,
        "Pagado": pagado,
        "nota": nota,
      };

I give up, i got not idea

CodePudding user response:

Try to use resp.body instead json.decode(resp.body).

CodePudding user response:

I wish I could know at which line you have Error but i guess it is at this line:

final tempProduct = Product.fromMap(value);

fromMap argument is Map but you are passing the values of your response map to fromMap. it is like you have this item in your map: "idRegistro":"4" and you pass 4 to fromMap. i wish i could explain it well in text. but your problem is that you are not passing your complete json Map to fromMap.

imagine that this is your response:

var map = {
"idRegistro":"4",
"idUsuario":"1",
"FechaRegistro":"2023-01-25T00:00:00",
"FechaGasto":"2023-01-25T00:00:00",
"TipoGasto":"OTRO",
"TipoTransaccion":"otro",
"Descripcion":"test",
"Monto":"3222.00",
"Nombre":"XXXXX",
"Ruta":"C:\DocumentosGastoApp\coin_dollar_money.ico",
"Pagado":false,
"nota":"Nada"
};

as you see your map size is 1. and by this code you are filling your list:

 var products = <Product>[];
          final tempProduct = Product.fromMap(map);
          products.add(tempProduct);

if you had a list of map something like this:

var map = [
{
"idRegistro":"4",
"idUsuario":"1",
"FechaRegistro":"2023-01-25T00:00:00",
"FechaGasto":"2023-01-25T00:00:00",
"TipoGasto":"OTRO",
"TipoTransaccion":"otro",
"Descripcion":"test",
"Monto":"3222.00",
"Nombre":"XXXXX",
"Ruta":"C:\DocumentosGastoApp\coin_dollar_money.ico",
"Pagado":false,
"nota":"Nada"
},

{
"idRegistro":"4",
"idUsuario":"1",
"FechaRegistro":"2023-01-25T00:00:00",
"FechaGasto":"2023-01-25T00:00:00",
"TipoGasto":"OTRO",
"TipoTransaccion":"otro",
"Descripcion":"test",
"Monto":"3222.00",
"Nombre":"XXXXX",
"Ruta":"C:\DocumentosGastoApp\coin_dollar_money.ico",
"Pagado":false,
"nota":"Nada"
}

];

you would do this:

 var products = <Product>[];

for(var item in map){

    final tempProduct = Product.fromMap(item);
          products.add(tempProduct);

}
         

because item is the map you should pass to the fromMap.

note to edit fromMap to this:

  factory Product.fromMap(Map<String, dynamic> json) =>
      Product(
        idRegistro: json["idRegistro"],
        idUsuario: json["idUsuario"],
        fechaRegistro: DateTime.parse(json["FechaRegistro"]),
        fechaGasto: DateTime.parse(json["FechaGasto"]),
        tipoGasto: json["TipoGasto"],
        tipoTransaccion: json["TipoTransaccion"],
        descripcion: json["Descripcion"],
        monto: json["Monto"],//here changed from monto to Monto
        nombre: json["Nombre"],
        ruta: json["ruta"],
        pagado: json["Pagado"],//here changed from pagado to Pagado
        nota: json["nota"],
        id: json["idRegistro"],
        //picture: json["picture"],
      );


because you don't have monto and pagado as lowerCase in your json and it is Monto and Pagado.

if you had any question, i'm here to help you my friend.

happy coding...

  • Related