Home > Blockchain >  How to do a toJson encode method on Dart/Flutter?
How to do a toJson encode method on Dart/Flutter?

Time:11-03

I used the fromJson method to recover a Struct with a List from Json decode http request and receiver it on my class, but now i want to do a reverse, i want to pass the data on my class to my toJson method and send him to a Json encode http POST. Please, i new on Dart/Flutter, someone know how to do this?

import 'dart:convert';

List<Itens> userFromJson(String str) =>
    List<Itens>.from(jsonDecode(str).map((x) => Itens.fromJson(x)));

class Coletas {

  final int codigo;
  final String dataIni;
  late String? dataFin;
  late String? status;
  final List<Itens> itemList;

  Coletas(
    {
      required this.dataIni,
      this.dataFin,
      this.status,
      required this.codigo,
      required this.itemList
    }
  );

  factory Coletas.fromJson(Map<String, dynamic> json) {
    return Coletas(
      dataIni: json['dtData'],
      codigo: json['iCodigo'],
      itemList: List<Itens>.from(json['stItens'].map((x) => Itens.fromJson(x))),
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'codigo': codigo,
      'dataIni': dataIni,
      'dataFin': dataFin,
      'status': status
    };
  }
}

class Itens {

  final int? id;
  final int codigo;
  late int quantidade;
  late String? status;
  final String codigoEAN;

  Itens({
    this.id,
    this.status,
    required this.codigo,
    required this.codigoEAN,
    required this.quantidade,
  });

  Map<String, dynamic> toJson(){
    return {
      'icodigo' : codigo,
      'sCodigoBarras': codigoEAN,
      'iQtd': quantidade
    };
  }

  factory Itens.fromJson(Map<String, dynamic> json) {
    return Itens(
      codigo: json['iCodigo'],
      codigoEAN: json['sCodigoBarras'],
      quantidade: json['iQtd'],
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'status': status,
      'codigo': codigo,
      'codigoEAN': codigoEAN,
      'quantidade': quantidade,
    };
  }
}

I tried to pass ever item on List separeted so, but not happen i expected.


  Map<String, dynamic> toJSon(Coletas value) =>
    {
      'dtData' : dataIni,
      'iCodigo': codigo,
      'stItens': [],
    };

CodePudding user response:

I think you should assign Coletas as

  Map<String, dynamic> toJSon(Coletas value) =>
    {
      'dtData' : value.dataIni,
      'iCodigo': value.codigo,
      'stItens': value.itemList,
    };

CodePudding user response:

For a better structure - format and use you can look at the flutter serialization documentation : https://docs.flutter.dev/development/data-and-backend/json.

It explains how to create your model and how to generate them to create fromJson and toJson Model based on the defined data. (https://docs.flutter.dev/development/data-and-backend/json#creating-model-classes-the-json_serializable-way)

It will helps you with your parsing - sending - receiving data.

  • Related