skip to Main Content

Im using dio to retrieve large json data from my Laravel backend, the problem is that, sometimes it works perfectly and it gets parsed correctly, and sometimes it returns:

FormatException: Unexpected character

Here is how im using dio:

class CartRepository {
  final dio = Dio(BaseOptions(
    baseUrl: API.apiURL,
    connectTimeout: 120 * 1000,
    receiveTimeout: 120 * 1000,
  ));

  Future<void> initializeToken() async {
    final token = await Storage.getToken();

    dio.options.headers['Content-Type'] = 'Application/json';
    dio.options.headers['Accept'] = 'Application/json';
    dio.options.headers['Authorization'] = token;
  }

  Future<Cart?> getCartProducts({required String storeUUID}) async {
    await initializeToken();

    try {
      final Response<String> response = await dio.get(API.apiURL + 'cart/$storeUUID');

      if (response.statusCode == 200) {
        final products = Cart.fromMap(jsonDecode(response.data!)); // <<<<<<<<

        return products;
      }
    } on DioError catch (exception) {
      if (exception.type == DioErrorType.response) {
        if (exception.response!.statusCode == 401) {
          throw UnauthorizedException();
        } else {
          throw ServerErrorException();
        }
      }

      log(exception.toString());
    }
  }
}

Here is an example of the error:

[log] DioError [DioErrorType.other]: FormatException: Unexpected
character (at character 30379)
…Dv0gII9i2AK.jpg","image_0_url:null,"image_1_url":"product_images/oKoNzu…

Notice that "image_0_url is missing the end quote.
The issue is that this same exact endpoint works well sometimes and doesnt work sometimes, and also, it never failed on postman, it always returns the correct json.

I have tested the returned json many times with online validated, also when i use postman to retrieve the exact same json data, it gets parsed correctly with never any issues.

PS: Please do comment on my implementation of the whole functionality if you notice a better way to do it

2

Answers


  1. response.data is already decoded by dio.

    The default value is json, dio will parse response string to json object automatically when the content-type of response is ‘application/json’.

    Login or Signup to reply.
  2. There will be cases where your server might misbehave. It’s always advised to handle null cases. In your model Model(url: json["json_url"]?? "https://a_fallback_imahlge.jpg&quot😉

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search