Expected a value of type 'List<dynamic>', but got one of type '_JsonMap'

Viewed 12914

When I try to json decode I get the error Expected a value of type 'List', but got one of type '_JsonMap'

My code:

  static Future<Response<Localizacao>> getLocalizacao(String cep) async {
    await Future.delayed(Duration(milliseconds: 200));
    try {
      Map<String, String> headers = {
        'Authorization': 'Token token=9e034db1f315356f30'};
      String protocol = 'https://cors-anywhere.herokuapp.com/';
      String uri =
          'https://www.cepaberto.com/api/v3/cep?cep=' + cep;
      final endpoint = "&format=json";
      String url = protocol + uri + endpoint;

      final response = await http.get(url, headers: headers);

      if (response.statusCode == 200) {

        final json = response.body;

        List list = (jsonDecode(json) as List<dynamic>) ;

        final local = list.map<Localizacao>((map) => Localizacao.fromJson(map)).toList();

        return Response(true, msg: "OK", result: local[0]);
      } else {
        return Response(false, msg: "Erro ao conectar no web service");
      }
    } catch (e) {

      return Response(false, msg: "Erro ao conectar no web service");
    }
  }

I tried other ways like:

List list = convert.json.decode(response.body);
List list = convert.json.decode(json);
2 Answers

Found out what the problem was.

I just had to add :

final json = "[" + response.body + "]";

Try this

 if (response.statusCode == 200) {
        print("IF responde==200");
        final json = response.body;
        print("IF rjson");
        Map<String, dynamic> map= jsonDecode(json) ; 
        print("IF converting json");
        final local = Localizacao.fromJson(map);
        print("IF mapping list");
        return Response(true, msg: "OK", result: local);
      } else {
        return Response(false, msg: "Erro ao conectar no web service");
      }
    } catch (e) {
      print("error in getLocalizacao: $e");
      return Response(false, msg: "Erro ao conectar no web service");
    }
Related