flutterdartdio

How to handle timeout error with Dio in Flutter?


I'm using Dio to handle APIs functions.

Here's my code:

  Future<List<ItemModel>> getItems() async {
    try {
      Response response = await dio.get("$_apiUrl$_itemEndPoint",
          options: Options(headers: {
            "Accept": 'application/json',
          }));

      List<ItemModel> _items = List<ItemModel>();

      response.data['data']?.forEach((c) {
        _items.add(ItemModel.fromMap(c));
      });
      return _items;
    } catch (e) {
      throw (e);
    }
  }

How can I catch an error based on timeout of send and receive?


Solution

  • Manage timeout exception using dio :

    ApiRepositary.dart

     class ApiRepositary {
      Dio dio;
    
      ApiRepositary() {
        if (dio == null) {
          BaseOptions options = new BaseOptions(
              baseUrl: "your base url",
              receiveDataWhenStatusError: true,
              connectTimeout: 60*1000, // 60 seconds
              receiveTimeout: 60*1000 // 60 seconds
              );
    
          dio = new Dio(options);
        }
      }
    
      Future<LoginResponse> getLoginDetails(var loginRequestData) async {
        try {
          Response response = await dio.post("/authenticate", data: loginRequestData);
          final LoginResponse loginResponse = LoginResponse.fromJson(response.data);
          return loginResponse;
        }on DioError  catch (ex) {
          if(ex.type == DioErrorType.CONNECT_TIMEOUT){
            throw Exception("Connection  Timeout Exception");
          }
          throw Exception(ex.message);
        }
      }
    
    }
    

    Example of handle exception :

    void checkLogin(){
     LoginRequest loginRequest = new LoginRequest(
                email: "abcd@gmail.com",password: "passs@123");
    
            var requestBody =jsonEncode(loginRequest);
            debugPrint("Request Data : $requestBody");
    
            _apiRepositary.getLoginDetails(requestBody).then((response){
              debugPrint("Login Success $response");
              //manage your response here 
    
            },
              onError: (exception){
                  //Handle exception message
                if(exception.message != null ){
    
                  debugPrint(exception.message); // Here you get : "Connection  Timeout Exception"
    
                }
              },
            );
    }