Search code examples
flutterdartnetworkinginterceptordio

Make proceeding functions remain uncalled when DioError


I want any of the functions bellow the call of API request (with Dio) remain uncalled when Dio catches error on ErrorInterceptor.

child: TextButton(
     child: Text('Submit'),
     onPressed: () async {
           final client = Dio();
           final baseOptions = BaseOptions(baseUrl: BASEURL);
           client.options = baseOptions;
           client.interceptors.add(InterceptorWrapper(
                  onError: (error, handler) async { await FlutterToast.showToast(msg: error.toString); }));
           await getUserData(client);
           
           // Skip whatever follows if dio catches error.
           Navigator.pop(context);
           }
)

Does anyone know how to do this?

I guess using a provider of some sort of state management tool would be easy, but I am looking for something I can complete inside onError: for simplicity.


Solution

  • You can create a helper class from which you can redirect all your api call. In the helper you can pass which api function you want to call and an success function which gets executed if the api call is success. Below is the sample of the helper function.

    class ApiHelper {
      static apiCallHelper(
          Future<dynamic> Function(Dio) apiCall, Function onSuccess) async {
        final client = Dio();
        final baseOptions = BaseOptions(baseUrl: BASEURL);
        client.options = baseOptions;
        client.interceptors
            .add(InterceptorsWrapper(onError: (error, handler) async {
          await FlutterToast.showToast(msg: error.toString);
        }));
        await apiCall(client);
        onSuccess();
      }
    }
    

    I have made a static function but you can make higher order function without class. I have put dynamic as a result for generic purpose. You can change it as per your need. Then you can make all api call through this.

    onPressed() {
      ApiHelper.apiCallHelper(
        getUserData,
        (data) {
          // whatever you want to do when api call is success
        },
      );
    }
    

    This should work as you intended.