How to handle timeout error with Dio in Flutter? How to handle timeout error with Dio in Flutter? dart dart

How to handle timeout error with Dio in Flutter?


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"            }          },        );}


Here's what I'm guessing by looking at one of their test files and their error class:

try {  await Dio().get("https://does.not.exist");} on DioError catch (e) {  if (e.type == DioErrorType.connectTimeout) {    // ...  }  if (e.type == DioErrorType.receiveTimeout) {    // ...  }}


You to define DIO option first:

 BaseOptions options = new BaseOptions(  baseUrl: "http://example.org",  connectTimeout: 5000,  receiveTimeout: 3000,);

then:

Dio dio = new Dio(options);var jsonNews = await dio.get(        'http://example.org/v2/everything?q=bitcoin&from=2020-01-24&sortBy=publishedAt&apiKey=7f3c604b6e2245c88se50lzx02dc9cac1e2');

Source :

https://pub.dev/packages/dio