0

I am using Dio to fetch/post some information from/to the API. What I want is that any time I call an API and it returns an error (401, 403, 404, 500, etc...), I want an alert to popup and inform the user with the error details. I added the necessary interceptor to intercept the error and get the required information to show, however I could not find a way to show the alert.

class HttpCustomClient {
  static Dio configureDio() {
    final dio = Dio();
    dio.options.baseUrl = AppConsts.baseUrl;

    dio.interceptors.add(InterceptorsWrapper(onError: ((exception, handler) {
      var errorText = exception.response!.data['error'];

      //Insert code here to show an alert with errorText

      return handler.next(exception);
    })));

    return dio;
  }
}

1 Answers1

1

No interceptors are not for that purpose, you don't need them to show dialog or popup when you get 40x or 500 response. You can sent different state for these response cases with flutter_bloc for example, and call showAlertDialog in BlocListener in UI code part. It is the best practise.

Jakhongir Anasov
  • 1,207
  • 7
  • 16
  • Is there a way to avoid having to call the Alert pop up on every single API call? What I am trying to do is that I write the code in the interceptor, this way I no longer need to worry about whether or not any API call fails, or if I create a new API I do not need to modify it in order to show an Alert if it fails – Osama El-Masri Jun 21 '23 at 08:23
  • Yes there is. You can just call showAlertDialog on that interceptor inside (exception, handler) {} Only problem you left is to call BuildContext globally from interceptor. – Jakhongir Anasov Jun 21 '23 at 09:06
  • And you can do it using navigatorKey. You need context to use showAlertDialog. So you put ncontext from navigatorKey. Look there: https://stackoverflow.com/questions/66139776/get-the-global-context-in-flutter – Jakhongir Anasov Jun 21 '23 at 09:09
  • Yes but showAlertDialog requires context to be passed, I even tried one_context but with no luck. – Osama El-Masri Jun 21 '23 at 09:09
  • And if my comment helped you, then please upvote&accept it. – Jakhongir Anasov Jun 21 '23 at 09:10
  • Probably we commented at same time. I wrote about how to get context. Please look for it. – Jakhongir Anasov Jun 21 '23 at 09:11
  • It is working as expected now, thank you – Osama El-Masri Jun 21 '23 at 09:16