SagarRawat
SagarRawat

Reputation: 169

Dio instance doesnt return a response when getting a API endpoint

I am trying to get a response from an Api but there is no response in return. Dio instance doesnt return a response when getting a API endpoint

import 'package:dio/dio.dart';

class DioService {
  static const baseUrl = "https://dictionaryapi.dev/";
  Dio dio = Dio();

  DioService() {
    initializeInterceptors();
  }

  initializeInterceptors() {
    dio.interceptors.add(InterceptorsWrapper(onError: (e, _) {
      print(e.message);
    }, onRequest: (r, _) {
      print(r.method);
      print(r.path);
    }, onResponse: (r, _) {
      print(r.data);
    }));
  }

  Future<Response> getRequest(String endPoint) async {
    Response response;
    try {
      response = await dio.get(endPoint);
      print(response.toString());
    } on DioError catch (e) {
      print(e);
      throw Exception(e.message);
    }
    return response;
  }
}

console :

I/flutter (17735): GET
I/flutter (17735): https://api.dictionaryapi.dev/api/v2/entries/en_US/dog

Upvotes: 3

Views: 4520

Answers (1)

Nitrodon
Nitrodon

Reputation: 3445

Your interceptor is routing the request into a black hole.

The second parameter to each interceptor method is a handler. In order to continue a request, the interceptor must pass (possibly modified) request options to the handler, and the same holds for the error and response handlers.

dio.interceptors.add(InterceptorsWrapper(onError: (e, handler) {
  print(e.message);
  handler.next(e);
}, onRequest: (r, handler) {
  print(r.method);
  print(r.path);
  handler.next(r);
}, onResponse: (r, handler) {
  print(r.data);
  handler.next(r);
}));

For logging in particular, note that Dio provides a LogInterceptor class, so you don't need to roll your own.

Upvotes: 12

Related Questions