Search code examples
flutterdartdio

Flutter API request sends multiple times which depends on how many of previous calls were


As in the title - I have a problem sending API requests. Every time I move to another widget with API interactions it sends unnecesary calls. For example: first widget call it´s API request once, second widget call it twice, third widget send his three times etc.

Every widget is prevented to send this request one time on initial, but still it does, more depending on previous calls and send only this request, not every previous + this. Have someone any idea why is this happening?


Solution

  • I fixed the problem, my dio.client was outside of class with requests and after putting him there everything works fine.

    EDIT: I made class called ServerApi which looked something like this:

    class ServerApi {
        ServerApi() {
        dio.interceptors.add(LogInterceptor(responseBody: true, requestBody: true));
        (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client) {
           client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
           return client;
        };
        }
    
      Future<bool> serverConnectionTest() async {
        try {
            final result = await InternetAddress.lookup(serverUrl);
            return result.isNotEmpty &&
        result[0].rawAddress.isNotEmpty;
            } on SocketException catch (_) {
              return false;
            }
        }
        <some request api, for example login, logout etc.>
    }
    

    And i had my dio outside of this class. Fix looked like this:

    class ServerApi{
        final Dio dio = Dio();
    // Same stuff as above
    }
    

    The problem: If you declare dio outside of your class with api requests (in my case ServerApi), everytime it will call next api request n+1 times, where n is the number of previous calls from aplication start.