1

I need to decode the data I receive as utf8. The codes are like this

Future<Products> Get Product() async {
     var response = await http.get(url);
     var decodedJson = json.decode(response.body);
     products = Products.fromJson(decodedJson);
     return products;
   }

I tried the solutions I saw. One of them told me to do it like this

 var response = await http.get(url,headers: {'Content-Type': 'application/json'});
 var decodedJson = json.decode(utf8.decode(response.bodyBytes));

When I do this, I get the following

errorException has occurred.
FormatException (FormatException: Missing extension byte (at offset 554))

) And it's look like enter image description here

  • Are you get data from API ? – Ravindra S. Patil Aug 09 '21 at 14:54
  • Seems like your `bodyBytes` does not contain valid UTF-8. Are you sure you are not going to set a charset on your request? What charset is set on the response? – julemand101 Aug 09 '21 at 14:54
  • @RavindraS.Patil Yes I m getting data and using it. But it is write ''ARAÇ TEMİZLEYİCİ'' instead of ''ARAÇ TEMÝZLEYÝCÝ'' – Bora Tan Demir Aug 09 '21 at 15:29
  • @julemand101 Actually, I don't understand exactly what you mean. I'm new to the world of developers. what do you mean by charset? – Bora Tan Demir Aug 09 '21 at 15:35
  • If you get data from API refer my answer [here](https://stackoverflow.com/a/68533647/13997210)or [here](https://stackoverflow.com/a/68594656/13997210) or [here](https://stackoverflow.com/a/68709502/13997210) hope it helps to you. – Ravindra S. Patil Aug 09 '21 at 15:42
  • @BoraTanDemir Is it possible to make a demo application connecting to the API (or demo API) which gives the same error you have? It is rather difficult to say for sure what you problem is without any way to debug. – julemand101 Aug 09 '21 at 15:48

1 Answers1

1

Try this code

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<Products> Get Product() async {
      final response = await http
          .get(Uri.parse(url));
    
      if (response.statusCode == 200) {
        // If the server did return a 200 OK response,
        // then parse the JSON.
        return Products.fromJson(jsonDecode(response.body));
      } else {
        // If the server did not return a 200 OK response,
        // then throw an exception.
        throw Exception('Failed to load Products');
      }
      
    }
  • I think OP is getting error response or anything different from success (200-299 codes). So this answer should help and fix the issue as you are stating if response is success (200). Probably error response returns empty body – Kohls Aug 09 '21 at 21:41