<<Flutter>> Doubt on return of Map - //Map <String, Dynamic>// - this returning: null

Asked

Viewed 645 times

-2

I will leave the code block --(Recovers api from https://viacep.com.br/, data listed on Cod, end of studies and training)inserir a descrição da imagem aqui

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';



class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

    String _resultado = "Resultado";


  _recuperarCep() async {

    //String cep = "01001000";
    String url = "https://viacep.com.br/ws/01001000/json/";
    http.Response response;

    response = await http.get(url);

    //Map<String, dynamic> retorno = json.decode( response.body );

    Map <String, dynamic> retorno = jsonDecode(response.body);

    String logradouro = retorno["Logradouro"];
    String complemento = retorno["Complemento"];
    String bairro = retorno["Bairro"];
    String localidade = retorno["Localidade"];


    setState(() {
      _resultado = "${logradouro},${complemento},${bairro},${localidade},";
    });

    print(
        "Resposta logradouro: ${logradouro} complemento ${complemento} bairro ${bairro} localidade ${localidade}"
   );

    //print("Resposta:"+ response.statusCode.toString());
    //print("Resposta:"+ response.body);

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Consumo de serviço web"),
      ),
      body: Container(
        padding: EdgeInsets.all(40),
        child: Column(
          children: <Widget>[
            Text(_resultado),
            RaisedButton(
              child: Text("Clique aqui"),
              onPressed: _recuperarCep,
            )
          ],
        ),
      ),

    );
  }
}

1 answer

1


Pay more attention to the API you are using... It returns this JSON below and you are reading it wrong.

{
  "cep": "01001-000",
  "logradouro": "Praça da Sé",
  "complemento": "lado ímpar",
  "bairro": "Sé",
  "localidade": "São Paulo",
  "uf": "SP",
  "unidade": "",
  "ibge": "3550308",
  "gia": "1004"
}

The problem is not the Map<> returned, but rather as you are reading the data from it...

Flutter is casesensitive, so...

Change it here

String logradouro = retorno["Logradouro"];
String complemento = retorno["Complemento"];
String bairro = retorno["Bairro"];
String localidade = retorno["Localidade"];

To

String logradouro = retorno["logradouro"];
String complemento = retorno["complemento"];
String bairro = retorno["bairro"];
String localidade = retorno["localidade"];
  • 1

    perfect worked out, it was an inattention of mine, I am very grateful for your help vlw thank you.

Browser other questions tagged

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