flutterretrofit2connection-timeout

How to set timeout for Api call using retrofit in flutter?


Where we can set timeout in below code? As you can see I am using retrofit for api call.

Dio Object

class DioObject{
  static Dio  getDio(){
    debugPrint("Bearer:- ${PrefHelper().pref?.getString(PrefHelper.AUTHORIZATION)}");
    final dio = Dio(); // Provide a dio instance
    dio.options.headers["Authorization"] =
    "Bearer ${PrefHelper().pref?.getString(PrefHelper.AUTHORIZATION)}"; // config your dio headers globally
    dio.options.headers["Content-Type"] =
    "application/json;charset=UTF-8"; // config your dio headers globally
    
    return dio;
  }

}

Api call

final client = RestClient(DioObject.getDio());
  
var response = await client.xyz();

Rest API

@RestApi(baseUrl: "*****/api")
abstract class RestClient {
  factory RestClient(Dio dio, {String baseUrl}) = _RestClient;

 

 @GET("/UserAccessPoints/")
  Future<CommonResponse> xyz();

}

Solution

  • You can do it the same way you added your custom headers, or doing it all at once with a BaseOptions object

      final dio = Dio();
    
      //Dio Options
      dio.options = BaseOptions(
        contentType: 'application/json',
        connectTimeout: 4000,
        sendTimeout: 4000,
        receiveTimeout: 10000,
        headers : ...
      );