View Arrays Data Items

Asked

Viewed 62 times

0

Model of the json:

class ListaPedido {
  int numero;
  String localEntrega;
  String dataHora;
  String formaPagamento;
  List<ItensPed> itens;

  ListaPedido({
    this.numero,
    this.localEntrega,
    this.dataHora,
    this.formaPagamento,
    this.itens,
  });

  ListaPedido.fromJson(Map<String, dynamic> json) {
    numero = json['numero'];
    localEntrega = json['local_entrega'];
    dataHora = json['data_hora'];
    formaPagamento = json['forma_pagamento'];
    if (json['Itens'] != null) {
      itens = new List<ItensPed>();
      json['Itens'].forEach((v) {
        itens.add(new ItensPed.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['numero'] = this.numero;
    data['local_entrega'] = this.localEntrega;
    data['data_hora'] = this.dataHora;
    data['forma_pagamento'] = this.formaPagamento;
    if (this.itens != null) {
      data['Itens'] = this.itens.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class ItensPed {
  String peduuid;
  String itemUid;
  String qtde;
  String valor;
  String valorTotal;
  String descrProduto;
  String tamanho;
  String textoOpc;

  ItensPed({
    this.peduuid,
    this.itemUid,
    this.qtde,
    this.valor,
    this.valorTotal,
    this.descrProduto,
    this.tamanho,
    this.textoOpc,
  });

  ItensPed.fromJson(Map<String, dynamic> json) {
    peduuid = json['peduuid'];
    itemUid = json['item_uid'];
    qtde = json['qtde'];
    valor = json['valor'];
    valorTotal = json['valor_total'];
    descrProduto = json['descr_produto'];
    tamanho = json['tamanho'];
    textoOpc = json['texto_opc'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['peduuid'] = this.peduuid;
    data['item_uid'] = this.itemUid;
    data['qtde'] = this.qtde;
    data['valor'] = this.valor;
    data['valor_total'] = this.valorTotal;
    data['descr_produto'] = this.descrProduto;
    data['tamanho'] = this.tamanho;
    data['texto_opc'] = this.textoOpc;
    return data;
  }
}

API via post where to get the data:

import 'dart:convert';
import 'package:cardapiomonitor/api/listar_pedido.dart';
import 'package:http/http.dart' as http;

class ListarPedidoApi {
  static Future<List<ListaPedido>> getListarPedido(String ppeduuid) async {
    var url = "http://192.168.1.12/api/ws_acoes.php";

    var response = await http.post(
      url,
      headers: <String, String>{
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
      body: <String, String>{
        'pedido': ppeduuid,
        'requisicao': 'LISTARPEDIDO',
      },
    );

    List listaResponseLP = json.decode(response.body);

    final listarpedidos = List<ListaPedido>();

    for (Map mapLP in listaResponseLP) {
      ListaPedido lp = ListaPedido.fromJson(mapLP);
      listarpedidos.add(lp);
    }

    return listarpedidos;
  }
}

I want to display the data of this array:

[
    {
        "numero": 722,
        "local_entrega": "Retirar no local",
        "data_hora": "2021-01-15 15:54:29",
        "forma_pagamento": "Dinheiro",
        "Itens": [
            {
                "item_uid": "4022acfe-f7cf-462d-b8bb-069a61cd8a9e",
                "qtde": "1.00",
                "valor": "2.00",
                "valor_total": "2.00",
                "descr_produto": "2-teste",
                "tamanho": "",
                "peduuid": "763145db-1610-4e71-9871-aeeecec1825a",
                "texto_opc": "Sem opcionais"
            },
            {
                "item_uid": "028c0f84-fa78-4685-9168-9ac5a24d0035",
                "qtde": "1.00",
                "valor": "29.99",
                "valor_total": "29.99",
                "descr_produto": "1-SUSHI",
                "tamanho": "",
                "peduuid": "763145db-1610-4e71-9871-aeeecec1825a",
                "texto_opc": "Sem opcionais"
            },
            {
                "item_uid": "574aed5e-033e-4fab-9d4b-dfc78f73669b",
                "qtde": "1.00",
                "valor": "3.00",
                "valor_total": "3.00",
                "descr_produto": "4-Porção de Batata Frita",
                "tamanho": "",
                "peduuid": "763145db-1610-4e71-9871-aeeecec1825a",
                "texto_opc": "Sem opcionais"
            }
        ]
    }
]

Could someone give me a tip on how to display this json, especially the items???

1 answer

1


I’ll give you an example of a JSON in the same format as your "item > sub-items", hence you implement it for your case...

I will use the following JSON:

    {
       "usuarios":[
          {
             "id":"001",
             "nome":"Matheus Ribeiro",
             "telefone":"5514981234567",
             "emails":[
                {
                   "email":"[email protected]",
                   "tipo":"contato"
                },
                {
                   "email":"[email protected]",
                   "tipo":"financeiro"
                }
             ]
          },
          {
             "id":"002",
             "nome":"Miranda",
             "telefone":"5514981765432",
             "emails":[
                {
                   "email":"[email protected]",
                   "tipo":"contato"
                },
                {
                   "email":"[email protected]",
                   "tipo":"financeiro"
                }
             ]
          }
       ]
    }

import 'dart:convert';
import 'dart:core';
import 'package:flutter/material.dart';


final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

  final String json = 
    """
    {
       "usuarios":[
          {
             "id":"001",
             "nome":"Matheus Ribeiro",
             "telefone":"5514981234567",
             "emails":[
                {
                   "email":"[email protected]",
                   "tipo":"contato"
                },
                {
                   "email":"[email protected]",
                   "tipo":"financeiro"
                }
             ]
          },
          {
             "id":"002",
             "nome":"Miranda",
             "telefone":"5514981765432",
             "emails":[
                {
                   "email":"[email protected]",
                   "tipo":"contato"
                },
                {
                   "email":"[email protected]",
                   "tipo":"financeiro"
                }
             ]
          }
       ]
    }
    """;
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {

 final jsonMap = jsonDecode(json);

  @override
  Widget build(BuildContext context) {
    List<Usuario> usuarios = (jsonMap["usuarios"] as List).map((usuario) => Usuario.fromJson(usuario as Map<String, dynamic> )).toList();
    return ListView.builder(
      itemCount: usuarios.length,
      itemBuilder: (_, index) {
        Usuario usuario = usuarios[index];
        return Card(
          child: Column(
            children: [
                Text("${usuario.id} - ${usuario.nome}"),
                Column(
                 children: usuario.emails.map((email) {
                    return Text("${email.email} (${email.tipo})");
                 }).toList(),
                )
            ],
         )
        );
      }
    );
  }
}

class Email {
  Email({this.email, this.tipo});

  final String email;
  final String tipo;
  
  factory Email.fromJson(Map<String, dynamic> json) => Email(
    email: json["email"] as String,
    tipo: json["tipo"]  as String);
}

class Usuario {
  Usuario({this.id, this.nome, this.telefone, this.emails});
 
  final String id;
  final String nome;
  final String telefone;
  final List<Email> emails;
  
  factory Usuario.fromJson(Map<String, dynamic> json) => Usuario(
    id: json["id"] as String,
    nome: json["nome"] as String,
    telefone: json["telefone"] as String,
    emails: (json["emails"] as List).map((conteudo) => Email.fromJson(conteudo as Map<String, dynamic>)).toList());
}

You can run this code on Dartpad

You can also take a look at my article Uncomplicating JSON on Flutter

  • vlw Matheus, it worked out here, I just had to modify some things because I was picking up via post, but it worked out, thank you very much.

  • If it helped solve your problem and you don’t want to wait for other answers, remember to mark how you accept the answer.

Browser other questions tagged

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