Home > Net >  utf-8 encoding in api result - dart/flutter
utf-8 encoding in api result - dart/flutter

Time:02-15

I'm reading an API that has latin characters (portuguese), but when displaying the results they appear distorted.

This is the original API content:

[{"id":23,"nome":"Feira de automóveis 2021","local":"Anhembi São Paulo","dataEvento":"2021-12-16","valorEntrada":"150.00","foto":null,"observacao":"Evento fictício para testes apenas"}]

And this is the result:

[{id: 23, nome: Feira de automóveis 2021, local: Anhembi São Paulo, dataEvento: 2021-12-16, valorEntrada: 150.00, foto: null, observacao: Evento fictício para testes apenas}]

Below the code I am using:

  Future<dynamic>? listar() async {
    final url =
        Uri.parse('https://www.limeiraweb.com.br/api_eventos/listar.php');
    final response = await http.get(url);
    if (response.statusCode == 200) {
      final jsonResponse = convert.jsonDecode(response.body);
      print(jsonResponse);
    }
  }

How to fix this problem?

CodePudding user response:

Either change/add this HTTP response header on the server:

content-type: application/json; charset=utf-8

Or force the encoding:

final jsonResponse = convert.jsonDecode(utf8.decode(response.bodyBytes));

CodePudding user response:

You can use this method

Utf8Decoder().convert(response.bodyBytes)

eg:-

      final url = Uri.parse('https://www.limeiraweb.com.br/api_eventos/listar.php');
  final response = await get(url);
  if (response.statusCode == 200) {
    final jsonResponse = jsonDecode(Utf8Decoder().convert(response.bodyBytes));
    print(jsonResponse);
  
  }

enter image description here OR

utf8.decode(response.bodyBytes);

eg:-

 final url = Uri.parse('https://www.limeiraweb.com.br/api_eventos/listar.php');
  final response = await get(url);
  if (response.statusCode == 200) {

    final jsonResponsed = jsonDecode(utf8.decode(response.bodyBytes));
    print(jsonResponsed);
  
  }
  • Related