Home > OS >  Error: A value of type 'DioClient' can't be returned from a function with return type
Error: A value of type 'DioClient' can't be returned from a function with return type

Time:09-15

I followed a tutorial on the internet just to learn how to intercept requests in flutter (Here is the link to the tutorial: https://dhruvnakum.xyz/networking-in-flutter-interceptors#comments-list). Their code seems to be working fine whereas mine can't compile. I keep having this error: **lib/data/network/dio_client.dart:7:27: Error: The method 'DioInterceptor' isn't defined for the class 'DioClient'.

  • 'DioClient' is from 'package:interceptor_blog/data/network/dio_client.dart' ('lib/data/network/dio_client.dart'). Try correcting the name to the name of an existing method, or defining a method named 'DioInterceptor'. _dio.interceptors.add(DioInterceptor());**

Here is the content of my dio_client.dart file:

import 'package:dio/dio.dart';

class DioClient {
  final _dio = Dio();

  DioClient() {
    _dio.interceptors.add(DioInterceptor());
  }

  Dio get dio => _dio;
}

HELP PLEASE!

CodePudding user response:

There is no DioInterceptor() method available in Dio package.

DioClient() { _dio.interceptors.add(InterceptorsWrapper()); }

Inside the InterceptorsWrapper you can modify the request, response, error as you need.

CodePudding user response:

Looking at the tutorial that you posted, the author states:

Ways of adding Interceptor

We can add interceptors in two ways : Using Built-in class [InterceptorsWrapper, QueuedInterceptorWrapper] and By extending custom class Let's add interceptor using the second way. Create a new file named dio_interceptor.dart file inside the network folder. Extend the custom DioInterceptor class with Interceptor class.

Have you tried creating the class DioInterceptor in your project? The author does provide an example implementation.

class DioInterceptor extends Interceptor {
  final _prefsLocator = getIt.get<SharedPreferenceHelper>();

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    options.headers['Authorization'] = _prefsLocator.getUserToken();
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // TODO: implement onResponse
    super.onResponse(response, handler);
  }

  @override
  void one rror(DioError err, ErrorInterceptorHandler handler) {
    // TODO: implement one rror
    super.onError(err, handler);
  }
}
  • Related